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
[1 of 11] Move the metric About sidebar components to data-studio-ui (#85097)
Alexander Polyankin6410b6b4d0ec
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.ednindex 4e43d5c155d..3c9505b5e50 100644--- a/.clj-kondo/config/modules/config.edn+++ b/.clj-kondo/config/modules/config.edn@@ -2219,6 +2219,7 @@:model/NativeQuerySnippet:model/Notification:model/Revision+ :model/Table:model/Timeline:model/User}}@@ -3824,7 +3825,7 @@enterprise/data-apps{:team "Embedding"- :api #{metabase-enterprise.data-apps.api metabase-enterprise.data-apps.core metabase-enterprise.data-apps.init}+ :api #{metabase-enterprise.data-apps.api metabase-enterprise.data-apps.init}:uses #{actionsapiapi-scope@@ -3848,7 +3849,6 @@:model/Card:model/Collection:model/DataPermissions- :model/Field:model/Permissions:model/Table}:model-exports #{:model/DataApp}}@@ -4292,7 +4292,6 @@task.historyutilwarehouse-schema-overlay- enterprise/data-appsenterprise/serializationenterprise/transforms.python}:model-exports #{:model/RemoteSyncTask}@@ -4569,6 +4568,8 @@lib.schemamodelspremium-features+ query-processor+ requestrevisionsrun-trackingsql-toolsdiff --git a/e2e/test/scenarios/data-apps/admin.cy.spec.ts b/e2e/test/scenarios/data-apps/admin.cy.spec.tsdeleted file mode 100644index 851c8236657..00000000000--- a/e2e/test/scenarios/data-apps/admin.cy.spec.ts+++ /dev/null@@ -1,154 +0,0 @@-import {- DATA_APP_DISPLAY_NAME as APP_DISPLAY_NAME,- DATA_APP_NAME as APP_NAME,-} from "e2e/support/helpers";-import type { DataApp } from "metabase-types/api";--import { DATA_APP_TEST_ENV as TEST_ENV } from "./helpers";--const { H } = cy;--describe("scenarios > data apps > admin management", () => {- beforeEach(() => {- H.restore();- cy.signInAsAdmin();- // `bleeding-edge` grants the `data-apps` premium feature; requires the EE build.- H.activateToken("bleeding-edge");- });-- it("Happy Path: lists a data app and renders it in its sandboxed iframe with real SDK data", () => {- H.mockDataApp(APP_NAME, {- displayName: APP_DISPLAY_NAME,- testEnv: TEST_ENV,- });-- cy.visit("/admin/settings/apps");- cy.findByRole("link", { name: APP_DISPLAY_NAME })- .scrollIntoView()- .should("be.visible");-- cy.intercept("POST", "/api/dataset").as("dataAppQuery");-- H.openDataApp(APP_NAME);- H.dataAppIframe(APP_DISPLAY_NAME).within(() => {- cy.findByRole("heading", { name: "Orders overview" }).should(- "be.visible",- );-- cy.findByTestId("orders-count", { timeout: 30000 })- .invoke("text")- .should("match", /^\d+$/);-- cy.findByText("Subtotal", { timeout: 30000 }).should("be.visible");- });-- // The iframe's query requests must be attributed to the data app, so- // query_execution analytics record which app ran them (EMB-2088).- cy.wait("@dataAppQuery").then(({ request }) => {- expect(request.headers["x-metabase-client"]).to.equal("data-app");- expect(request.headers["x-metabase-client-identifier"]).to.equal(- APP_NAME,- );- });- });-- it("dismisses the promo banner and keeps it hidden across a reload", () => {- cy.intercept("GET", "/api/ee/apps/repo-status", { configured: true });- cy.intercept("GET", "/api/ee/apps", []);- cy.intercept(- "PUT",- "/api/user-key-value/namespace/user_acknowledgement/key/data-apps-admin-settings-banner",- ).as("ackBanner");-- cy.visit("/admin/settings/apps");-- H.main()- .findByText(/AI-generated React apps/)- .should("be.visible");- cy.findByRole("button", { name: "Dismiss" }).click();- cy.wait("@ackBanner");- H.main()- .findByText(/AI-generated React apps/)- .should("not.exist");-- // The dismissal persists (a real user-key-value write), so a reload keeps it hidden.- cy.reload();- cy.findByRole("heading", { name: "Data apps" }).should("be.visible");- H.main()- .findByText(/AI-generated React apps/)- .should("not.exist");- });-- describe("outdated apps", () => {- // Only a bump of the supported version makes a real app outdated, so the flag- // the API computes is patched onto a real app's responses instead.- const OUTDATED_APP = "good";-- function markAppOutdated() {- H.pullExampleDataApps();- cy.request<DataApp>("GET", `/api/ee/apps/${OUTDATED_APP}`)- .its("body.display_name")- .as("outdatedAppName");-- cy.intercept("GET", "/api/ee/apps", (req) => {- req.continue((res) => {- res.body = res.body.map((app: DataApp) =>- app.name === OUTDATED_APP- ? { ...app, version: 1, outdated: true }- : app,- );- });- });- cy.intercept(- { method: "GET", pathname: `/api/ee/apps/${OUTDATED_APP}` },- (req) => {- req.continue((res) => {- res.body = { ...res.body, version: 1, outdated: true };- });- },- );- }-- it("badges an outdated app and refuses to open it", () => {- markAppOutdated();-- cy.visit("/admin/settings/apps");-- cy.get<string>("@outdatedAppName").then((displayName) => {- cy.findByTestId(`data-app-list-item-${OUTDATED_APP}`)- .scrollIntoView()- .within(() => {- cy.findByText("Outdated").should("be.visible");- cy.findByText(displayName).should("be.visible");- cy.findByRole("link", { name: displayName }).should("not.exist");- });- });-- H.openDataApp(OUTDATED_APP);- H.main().findByText("This data app is outdated").should("be.visible");- cy.get("iframe").should("not.exist");- });- });-});--describe("scenarios > data apps > upsell (OSS)", { tags: "@OSS" }, () => {- beforeEach(() => {- H.restore();- cy.signInAsAdmin();- // No token: on the OSS build the `data-apps` feature is unavailable, so the- // settings page shows the upsell instead of the management UI.- });-- it("shows the data-apps upsell instead of the management UI, and marks the Data apps settings nav item with an upsell gem", () => {- cy.visit("/admin/settings/apps");-- H.main().within(() => {- cy.findByText("Build custom data apps").should("be.visible");- cy.findByText("Try for free").should("be.visible");- });-- cy.findByRole("link", { name: /Data apps/ }).within(() => {- cy.findByTestId("upsell-gem").should("be.visible");- });- });-});diff --git a/e2e/test/scenarios/data-apps/data-studio-permissions.cy.spec.ts b/e2e/test/scenarios/data-apps/data-studio-permissions.cy.spec.tsnew file mode 100644index 00000000000..450030c26e6--- /dev/null+++ b/e2e/test/scenarios/data-apps/data-studio-permissions.cy.spec.ts@@ -0,0 +1,229 @@+import { SAMPLE_DB_ID } from "e2e/support/cypress_data";+import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";+import {+ ALL_USERS_GROUP_ID,+ COLLECTION_GROUP_ID,+} from "e2e/support/cypress_sample_instance_data";+import type { GroupInfo } from "metabase-types/api";++const { H } = cy;+const { ORDERS_ID } = SAMPLE_DATABASE;++const EMPTY_STATE_TEXT =+ "Only admins can open this app. Add groups to give people in them access.";++describe("scenarios > data apps > data studio permissions", () => {+ beforeEach(() => {+ H.restore();+ cy.signInAsAdmin();+ H.activateToken("bleeding-edge");+ });++ describe("group access", () => {+ const APP_NAME = "group-access-test";+ const APP_DISPLAY_NAME = "Group Access Test";+ const APP_LINK_REGEX = new RegExp(`${APP_DISPLAY_NAME}$`);++ beforeEach(() => {+ H.setupGitSync();+ H.copySyncedCollectionFixture();+ H.updateSetting("remote-sync-custom-collections-enabled", true);++ H.writeDataAppResources(H.LOCAL_GIT_PATH, {+ collection: H.dataAppRepresentations.collection(+ "groupAccessAppColl001",+ `Data App: ${APP_DISPLAY_NAME}`,+ ),+ });++ // A built bundle and manifest let remote sync publish a real app, so+ // access goes through the real permission checks.+ cy.task<string>("buildDataApp", { appName: APP_NAME }).then((bundle) =>+ cy.writeFile(+ `${H.LOCAL_GIT_PATH}/data_apps/${APP_NAME}/dist/index.js`,+ bundle,+ ),+ );+ cy.readFile(+ `e2e/support/assets/data-apps/${APP_NAME}/data_app.yaml`,+ ).then((manifest) =>+ cy.writeFile(+ `${H.LOCAL_GIT_PATH}/data_apps/${APP_NAME}/data_app.yaml`,+ manifest,+ ),+ );++ H.commitToRepo("Add a data app for testing group access");+ H.configureGitAndPullChanges("read-write");++ cy.request("GET", `/api/permissions/group/${COLLECTION_GROUP_ID}`)+ .its("body.name")+ .as("groupName");+ });++ it("grants and revokes access to an app when adding and removing a group", () => {+ cy.log("the app is hidden and access is denied by default");+ cy.signIn("nodata");+ assertAppIsHidden();+ assertAppAccessDenied();++ cy.signInAsAdmin();+ cy.intercept("POST", `/api/ee/apps/${APP_NAME}/groups`).as("addGroups");+ cy.visit(`/data-studio/apps/${APP_NAME}/permissions`);+ H.main().findByText(EMPTY_STATE_TEXT).should("be.visible");++ cy.log("add a group to the app");+ H.main().findByRole("button", { name: "Add groups" }).click();+ H.modal().findByRole("textbox", { name: "Groups" }).click();+ cy.get<string>("@groupName").then((name) =>+ cy.findByRole("option", { name }).click(),+ );+ H.modal().findByRole("button", { name: "Add" }).click();+ cy.wait("@addGroups");++ cy.get<string>("@groupName").then((name) =>+ H.main().findByText(name).should("be.visible"),+ );++ cy.log("members of the group can open the app");+ cy.signIn("nodata");+ visitHome();+ H.navigationSidebar()+ .findByRole("link", { name: APP_LINK_REGEX })+ .should("be.visible")+ .invoke("removeAttr", "target")+ .click();+ assertAppIsRendered();++ cy.log("remove the group after confirming");+ cy.signInAsAdmin();+ cy.intercept("DELETE", `/api/ee/apps/${APP_NAME}/groups/*`).as(+ "removeGroup",+ );+ cy.visit(`/data-studio/apps/${APP_NAME}/permissions`);+ cy.get<string>("@groupName").then((name) =>+ H.main()+ .findByRole("button", { name: `${name} options` })+ .click(),+ );+ H.popover()+ .findByRole("menuitem", { name: /Remove access/ })+ .click();+ H.modal().findByRole("button", { name: "Remove access" }).click();+ cy.wait("@removeGroup");+ H.main().findByText(EMPTY_STATE_TEXT).should("be.visible");++ cy.log("admins can still open the app");+ H.openDataApp(APP_NAME);+ assertAppIsRendered();++ cy.log("members of the removed group lose access");+ cy.signIn("nodata");+ assertAppIsHidden();+ assertAppAccessDenied();+ });++ function visitHome() {+ cy.intercept("GET", "/api/ee/apps?available=true").as("availableApps");+ cy.visit("/");+ cy.wait("@availableApps");+ H.navigationSidebar()+ .findByRole("listitem", { name: "Home" })+ .should("be.visible");+ }++ function assertAppIsHidden() {+ visitHome();+ H.navigationSidebar()+ .findByRole("link", { name: APP_LINK_REGEX })+ .should("not.exist");+ }++ function assertAppAccessDenied() {+ H.openDataApp(APP_NAME);+ H.main()+ .findByText("You don’t have access to this data app")+ .should("be.visible");+ }++ function assertAppIsRendered() {+ H.dataAppIframe(APP_DISPLAY_NAME)+ .findByRole("heading", { name: "Group access app" })+ .should("be.visible");+ }+ });++ describe("missing data access", () => {+ const APP_NAME = "good";+ const GROUP_NAME = "Finches";+ const DATA_ACCESS_PERMISSION_INDEX = 0;++ beforeEach(() => {+ H.pullExampleDataApps({+ goodAppCards: [+ H.dataAppRepresentations.card({+ entityId: "warningsOrdersCard000",+ name: "Orders",+ type: "question",+ collection: "goodAppCollection0000",+ table: ["Sample Database", "PUBLIC", "ORDERS"],+ }),+ ],+ });+ H.waitForBackfillComplete();++ cy.request<GroupInfo>("POST", "/api/permissions/group", {+ name: GROUP_NAME,+ }).then(({ body: group }) => {+ H.blockUserGroupPermissions(ALL_USERS_GROUP_ID);+ H.blockUserGroupPermissions(group.id);+ cy.request("POST", `/api/ee/apps/${APP_NAME}/groups`, {+ group_ids: [group.id],+ });+ });+ });++ it("shows the tables a group can't view, links to their permissions, and clears once access is granted", () => {+ cy.visit(`/data-studio/apps/${APP_NAME}/permissions`);++ H.main()+ .findByRole("row", { name: new RegExp(GROUP_NAME) })+ .findByText("Missing 1 table")+ .should("be.visible")+ .click();++ cy.findByTestId("data-app-group-sidebar").within(() => {+ cy.findByRole("heading", { name: GROUP_NAME }).should("be.visible");+ cy.findByRole("region", { name: "Missing tables" }).within(() => {+ cy.findByText("Sample Database").should("be.visible");+ cy.findByText("PUBLIC").should("be.visible");+ cy.findByText("Orders").click();+ });+ });++ H.popover()+ .findByRole("menuitem", { name: /Change permissions/ })+ .should("have.attr", "href")+ .and("include", `/admin/permissions/data/database/${SAMPLE_DB_ID}/`)+ .and("include", `/table/${ORDERS_ID}`);++ cy.log("grant access to the table");+ cy.visit(+ `/admin/permissions/data/database/${SAMPLE_DB_ID}/schema/PUBLIC/table/${ORDERS_ID}`,+ );+ H.assertPermissionForItem(+ GROUP_NAME,+ DATA_ACCESS_PERMISSION_INDEX,+ "Blocked",+ );+ H.modifyPermission(GROUP_NAME, DATA_ACCESS_PERMISSION_INDEX, "Can view");+ H.savePermissions();++ cy.visit(`/data-studio/apps/${APP_NAME}/permissions`);+ H.main()+ .findByRole("row", { name: new RegExp(GROUP_NAME) })+ .findByText("All tables")+ .should("be.visible");+ });+ });+});diff --git a/e2e/test/scenarios/data-apps/data-studio.cy.spec.ts b/e2e/test/scenarios/data-apps/data-studio.cy.spec.tsnew file mode 100644index 00000000000..ac99a9c5f7a--- /dev/null+++ b/e2e/test/scenarios/data-apps/data-studio.cy.spec.ts@@ -0,0 +1,153 @@+import {+ DATA_APP_DISPLAY_NAME as APP_DISPLAY_NAME,+ DATA_APP_NAME as APP_NAME,+} from "e2e/support/helpers";+import type { DataApp } from "metabase-types/api";++import { DATA_APP_TEST_ENV as TEST_ENV } from "./helpers";++const { H } = cy;++const SYNCED_APP_NAME = "good";+const SYNCED_APP_DISPLAY_NAME = "Good App";++describe("scenarios > data apps > data studio", () => {+ beforeEach(() => {+ H.restore();+ cy.signInAsAdmin();+ // `bleeding-edge` grants the `data-apps` premium feature; requires the EE build.+ H.activateToken("bleeding-edge");+ });++ it("lists a data app and previews it on the app's overview", () => {+ H.mockDataApp(APP_NAME, {+ displayName: APP_DISPLAY_NAME,+ testEnv: TEST_ENV,+ });++ cy.intercept("POST", "/api/dataset").as("dataAppQuery");++ cy.visit("/data-studio/apps");+ H.main().findByText(APP_DISPLAY_NAME).click();++ cy.location("pathname").should("eq", `/data-studio/apps/${APP_NAME}`);+ H.dataAppIframe(APP_DISPLAY_NAME).within(() => {+ cy.findByRole("heading", { name: "Orders overview" }).should(+ "be.visible",+ );+ cy.findByTestId("orders-count", { timeout: 30000 })+ .invoke("text")+ .should("match", /^\d+$/);+ });++ // The iframe's query requests must be attributed to the data app, so+ // query_execution analytics record which app ran them (EMB-2088).+ cy.wait("@dataAppQuery").then(({ request }) => {+ expect(request.headers["x-metabase-client"]).to.equal("data-app");+ expect(request.headers["x-metabase-client-identifier"]).to.equal(+ APP_NAME,+ );+ });+ });++ it("makes an app a draft and live again", () => {+ H.pullExampleDataApps();+ cy.intercept("PUT", `/api/ee/apps/${SYNCED_APP_NAME}`).as("updateGoodApp");++ cy.visit(`/data-studio/apps/${SYNCED_APP_NAME}`);+ cy.findByTestId("data-app-about-sidebar")+ .findByText("Live")+ .should("be.visible");++ cy.findByRole("button", { name: "Data app options" }).click();+ H.popover()+ .findByRole("menuitem", { name: /Make draft/ })+ .click();+ H.modal()+ .findByText(`Make ${SYNCED_APP_DISPLAY_NAME} a draft?`)+ .should("be.visible");+ H.modal().findByRole("button", { name: "Make draft" }).click();+ cy.wait("@updateGoodApp");++ cy.findByTestId("data-app-about-sidebar")+ .findByText("Draft")+ .should("be.visible");++ cy.findByRole("button", { name: "Data app options" }).click();+ H.popover()+ .findByRole("menuitem", { name: /Make live/ })+ .click();+ H.modal().findByRole("button", { name: "Make live" }).click();+ cy.wait("@updateGoodApp");++ cy.findByTestId("data-app-about-sidebar")+ .findByText("Live")+ .should("be.visible");+ });++ it("lists the app's questions and opens one", () => {+ H.pullExampleDataApps();++ cy.visit(`/data-studio/apps/${SYNCED_APP_NAME}`);+ H.main().findByRole("link", { name: "Questions" }).click();+ H.main().findByText("Orders").click();++ cy.location("pathname").should(+ "match",+ new RegExp(`^/data-studio/apps/${SYNCED_APP_NAME}/questions/\\d+$`),+ );+ cy.findByTestId("data-app-question-overview")+ .findByRole("link", { name: "Questions" })+ .should(+ "have.attr",+ "href",+ `/data-studio/apps/${SYNCED_APP_NAME}/questions`,+ );+ });++ describe("outdated apps", () => {+ // Only a bump of the supported version makes a real app outdated, so the flag+ // the API computes is patched onto a real app's responses instead.+ function markAppOutdated() {+ H.pullExampleDataApps();++ cy.intercept("GET", "/api/ee/apps", (req) => {+ req.continue((res) => {+ res.body = res.body.map((app: DataApp) =>+ app.name === SYNCED_APP_NAME+ ? { ...app, version: 1, outdated: true }+ : app,+ );+ });+ });+ cy.intercept(+ { method: "GET", pathname: `/api/ee/apps/${SYNCED_APP_NAME}` },+ (req) => {+ req.continue((res) => {+ res.body = { ...res.body, version: 1, outdated: true };+ });+ },+ );+ }++ it("marks an outdated app in the list, offers no way to open it there, and refuses to open it", () => {+ markAppOutdated();++ cy.visit("/data-studio/apps");+ H.main()+ .findByRole("row", { name: new RegExp(SYNCED_APP_DISPLAY_NAME) })+ .within(() => {+ cy.findByText("Live, outdated").should("be.visible");+ cy.findByRole("button", { name: "Data app options" }).click();+ });+ H.popover().within(() => {+ cy.findByRole("menuitem", { name: /Make draft/ }).should("be.visible");+ cy.findByRole("menuitem", { name: /Open app/ }).should("not.exist");+ });++ H.openDataApp(SYNCED_APP_NAME);+ H.main().findByText("This data app is outdated").should("be.visible");+ cy.get("iframe").should("not.exist");+ });+ });+});diff --git a/e2e/test/scenarios/data-apps/group-access-warnings.cy.spec.ts b/e2e/test/scenarios/data-apps/group-access-warnings.cy.spec.tsdeleted file mode 100644index d2ea12e2bb4..00000000000--- a/e2e/test/scenarios/data-apps/group-access-warnings.cy.spec.ts+++ /dev/null@@ -1,115 +0,0 @@-import { SAMPLE_DB_ID } from "e2e/support/cypress_data";-import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";-import { ALL_USERS_GROUP_ID } from "e2e/support/cypress_sample_instance_data";-import type { GroupInfo } from "metabase-types/api";--const { H } = cy;-const { ORDERS_ID } = SAMPLE_DATABASE;--const APP_NAME = "good";--const GROUP_NAME = "Finches";-const GROUP_MATCHER = new RegExp(GROUP_NAME);--const DATA_ACCESS_PERMISSION_INDEX = 0;--describe("scenarios > data apps > group access warnings (EMB-2416)", () => {- beforeEach(() => {- H.restore();- cy.signInAsAdmin();- H.activateToken("bleeding-edge");-- H.pullExampleDataApps({- goodAppCards: [- H.dataAppRepresentations.card({- entityId: "warningsOrdersCard000",- name: "Orders",- type: "question",- collection: "goodAppCollection0000",- table: ["Sample Database", "PUBLIC", "ORDERS"],- }),- ],- });- H.waitForBackfillComplete();-- cy.request<GroupInfo>("POST", "/api/permissions/group", {- name: GROUP_NAME,- })- .its("body")- .as("group");-- H.blockUserGroupPermissions(ALL_USERS_GROUP_ID);- cy.get<GroupInfo>("@group").then(({ id }) =>- H.blockUserGroupPermissions(id),- );- });-- it("shows missing table access after assignment and clears it after granting data permissions", () => {- cy.visit(`/admin/settings/apps/${APP_NAME}/groups`);-- H.main().findByText("No groups have access yet").should("be.visible");-- H.main().findByRole("button", { name: "Add groups" }).click();- H.main()- .findByRole("textbox", { name: "Search for groups to add" })- .click();-- cy.findByRole("option", { name: GROUP_NAME }).click();- cy.findByTestId("data-app-groups-card")- .findByRole("button", { name: "Add" })- .click();-- cy.log("some table accesses are missing initially");- H.main()- .findByRole("row", { name: GROUP_MATCHER })- .findByRole("button", { name: "Missing data access" })- .realHover();-- cy.log("database and table should be visible in card");- cy.findByTestId("data-access-warning-popover").within(() => {- cy.findByText(- `${GROUP_NAME} doesn’t have permission to view these tables used in this app:`,- ).should("be.visible");-- cy.findByRole("link", { name: "Sample Database" }).should("be.visible");-- cy.findByRole("link", { name: "Orders" }).should("be.visible").click();- });-- cy.log("orders table link navigates to the table permission page");- cy.location("pathname")- .should("include", `/admin/permissions/data/database/${SAMPLE_DB_ID}/`)- .and("include", `/table/${ORDERS_ID}`);-- H.assertPermissionForItem(- GROUP_NAME,- DATA_ACCESS_PERMISSION_INDEX,- "Blocked",- );-- cy.log("grant access to the table");- H.modifyPermission(GROUP_NAME, DATA_ACCESS_PERMISSION_INDEX, "Can view");- H.savePermissions();-- cy.intercept(- "GET",- `/api/ee/apps/${APP_NAME}/group-permission-warnings`,- ).as("groupWarnings");-- cy.go("back");- cy.location("pathname").should(- "equal",- `/admin/settings/apps/${APP_NAME}/groups`,- );-- cy.log("group warnings should be gone");- cy.wait("@groupWarnings").its("response.body").should("deep.equal", []);-- cy.log("group warnings should not show in the ui");- H.main()- .findByRole("row", { name: GROUP_MATCHER })- .should("be.visible")- .findByRole("button", { name: "Missing data access" })- .should("not.exist");- });-});diff --git a/e2e/test/scenarios/data-apps/group-access.cy.spec.ts b/e2e/test/scenarios/data-apps/group-access.cy.spec.tsdeleted file mode 100644index 3324ee96a81..00000000000--- a/e2e/test/scenarios/data-apps/group-access.cy.spec.ts+++ /dev/null@@ -1,157 +0,0 @@-import { COLLECTION_GROUP_ID } from "e2e/support/cypress_sample_instance_data";--const { H } = cy;--const APP_NAME = "group-access-test";-const APP_DISPLAY_NAME = "Group Access Test";-const APP_LINK_REGEX = new RegExp(`${APP_DISPLAY_NAME}$`);--describe("scenarios > data apps > group access (EMB-2415)", () => {- beforeEach(() => {- H.restore();- cy.signInAsAdmin();- H.activateToken("bleeding-edge");-- H.setupGitSync();- H.copySyncedCollectionFixture();- H.updateSetting("remote-sync-custom-collections-enabled", true);-- H.writeDataAppResources(H.LOCAL_GIT_PATH, {- collection: H.dataAppRepresentations.collection(- "groupAccessAppColl001",- `Data App: ${APP_DISPLAY_NAME}`,- ),- });-- // commit a built bundle and manifest so remote sync publishes a- // real app, to use real permission checks.- cy.task<string>("buildDataApp", { appName: APP_NAME }).then((bundle) =>- cy.writeFile(- `${H.LOCAL_GIT_PATH}/data_apps/${APP_NAME}/dist/index.js`,- bundle,- ),- );-- cy.readFile(`e2e/support/assets/data-apps/${APP_NAME}/data_app.yaml`).then(- (manifest) =>- cy.writeFile(- `${H.LOCAL_GIT_PATH}/data_apps/${APP_NAME}/data_app.yaml`,- manifest,- ),- );-- H.commitToRepo("Add data apps for testing group accesses");- H.configureGitAndPullChanges("read-write");-- cy.request("GET", `/api/ee/apps/${APP_NAME}`)- .its("body")- .should("include", {- name: APP_NAME,- display_name: APP_DISPLAY_NAME,- enabled: true,- });-- cy.request("GET", `/api/permissions/group/${COLLECTION_GROUP_ID}`)- .its("body.name")- .as("groupName");- });-- it("changes accesses to data apps when assigning and removing groups", () => {- cy.log("app is hidden and access is denied by default");- cy.signIn("nodata");- assertAppIsHidden();- assertAppAccessDenied();-- cy.signInAsAdmin();- cy.visit("/admin/settings/apps");-- cy.findByTestId(`data-app-list-item-${APP_NAME}`)- .findByRole("button", { name: `Actions for ${APP_DISPLAY_NAME}` })- .click();-- H.popover().findByRole("menuitem", { name: "Manage group access" }).click();- H.main().findByText("No groups have access yet").should("be.visible");-- cy.findByRole("button", { name: "Add groups" }).click();- cy.findByRole("textbox", { name: "Search for groups to add" }).click();-- cy.log("add a group to the data app");- cy.get<string>("@groupName").then((name) =>- cy.findByRole("option", { name }).click(),- );-- cy.findByTestId("data-app-groups-card")- .findByRole("button", { name: "Add" })- .click();-- cy.get<string>("@groupName").then((name) =>- H.main()- .findByRole("button", { name: `Remove ${name}`, timeout: 10000 })- .should("be.visible"),- );-- cy.log("the group should let members access the app");- cy.signIn("nodata");- visitHome();-- H.navigationSidebar()- .findByRole("link", { name: APP_LINK_REGEX })- .should("be.visible")- .invoke("removeAttr", "target")- .click();-- assertAppIsRendered();-- cy.log("remove the group");- cy.signInAsAdmin();- cy.visit(`/admin/settings/apps/${APP_NAME}/groups`);- cy.get<string>("@groupName").then((name) =>- cy.findByRole("button", { name: `Remove ${name}` }).click(),- );-- H.main()- .findByText("No groups have access yet", { timeout: 10000 })- .should("be.visible");-- cy.log("admins still can access the apps");- H.openDataApp(APP_NAME);- assertAppIsRendered();-- cy.log("the app access is revoked after the group is removed");- cy.signIn("nodata");- assertAppIsHidden();- assertAppAccessDenied();- });-});--function visitHome() {- cy.intercept("GET", "/api/ee/apps?available=true").as("availableApps");- cy.visit("/");- cy.wait("@availableApps");-- H.navigationSidebar()- .findByRole("listitem", { name: "Home" })- .should("be.visible");-}--function assertAppIsHidden() {- visitHome();-- H.navigationSidebar()- .findByRole("link", { name: APP_LINK_REGEX })- .should("not.exist");-}--function assertAppAccessDenied() {- H.openDataApp(APP_NAME);-- H.main()- .findByText("You don’t have access to this data app")- .should("be.visible");-}--function assertAppIsRendered() {- H.dataAppIframe(APP_DISPLAY_NAME)- .findByRole("heading", { name: "Group access app" })- .should("be.visible");-}diff --git a/e2e/test/scenarios/data-apps/sync.cy.spec.ts b/e2e/test/scenarios/data-apps/sync.cy.spec.tsindex 5e00406a37a..8de82aee11a 100644--- a/e2e/test/scenarios/data-apps/sync.cy.spec.ts+++ b/e2e/test/scenarios/data-apps/sync.cy.spec.ts@@ -21,17 +21,10 @@ describe("scenarios > data apps > repo sync", () => {H.commitToRepo("Add data apps");H.configureGitAndPullChanges("read-write");- cy.visit("/admin/settings/apps");- cy.findByTestId("admin-layout-content").within(() => {- cy.findByTestId("data-app-list-item-good")- .scrollIntoView()- .within(() => {- cy.findByRole("link", { name: "Good App" }).should("be.visible");- cy.findByText("A well-formed app that syncs cleanly").should(- "be.visible",- );- });- cy.findByTestId("data-app-list-item-second-app").should("exist");+ cy.visit("/data-studio/apps");+ H.main().within(() => {+ cy.findByRole("row", { name: /Good App/ }).should("be.visible");+ cy.findByRole("row", { name: /Second App/ }).should("be.visible");});cy.request("GET", "/api/ee/apps").then(({ body: apps }) => {diff --git a/enterprise/backend/src/metabase_enterprise/data_apps/core.clj b/enterprise/backend/src/metabase_enterprise/data_apps/core.cljindex 0a62d4e106d..1d2f78b4a3b 100644--- a/enterprise/backend/src/metabase_enterprise/data_apps/core.clj+++ b/enterprise/backend/src/metabase_enterprise/data_apps/core.clj@@ -1,17 +1,10 @@(ns metabase-enterprise.data-apps.core- "What other modules may ask the data-apps module: what the files of an app's collection may hold."+ "What other modules may ask the data-apps module: whether a user can open an app."(:require[metabase-enterprise.data-apps.db :as data-apps.db]- [metabase-enterprise.data-apps.resource-validation :as resource-validation][metabase.api.common :as api][metabase.models.interface :as mi]- [metabase.premium-features.core :refer [defenterprise]]- [potemkin :as p]))--(p/import-vars- [resource-validation- problems- warnings])+ [metabase.premium-features.core :refer [defenterprise]]))(defenterprise check-data-app-access!"Checks that the user can read the app: a member of an assigned group while it is enabled, or a superuser."diff --git a/enterprise/backend/src/metabase_enterprise/data_apps/db.clj b/enterprise/backend/src/metabase_enterprise/data_apps/db.cljindex be9bb3986b4..b3dfadf02fd 100644--- a/enterprise/backend/src/metabase_enterprise/data_apps/db.clj+++ b/enterprise/backend/src/metabase_enterprise/data_apps/db.clj@@ -55,16 +55,22 @@[slug :- :string](t2/exists? :model/DataApp :name slug))-(mu/defn data-app-entity-id-named- "The `:entity_id` of the DataApp named `slug`, or nil."- [slug :- :string]- (t2/select-one-fn :entity_id :model/DataApp :name slug))-(mu/defn resource-collection?"Whether the Collection with `collection-id` is the resource collection of a DataApp."[collection-id :- pos-int?](t2/exists? :model/DataApp :resource_collection_id collection-id))+(mu/defn other-app-has-collection?+ "Whether a DataApp other than the one with `app-id`, or any when it is nil, has the Collection with `collection-id`."+ [collection-id :- pos-int?+ app-id :- [:maybe pos-int?]]+ (t2/exists? :model/DataApp :resource_collection_id collection-id :id [:not= (or app-id -1)]))++(mu/defn data-apps-namespace-collection?+ "Whether the Collection with `collection-id` is in the data-apps namespace."+ [collection-id :- pos-int?]+ (t2/exists? :model/Collection :id collection-id :namespace "data-apps"))+(mu/defn insert-data-app-returning-pk! :- ms/PositiveInt"Insert the DataApp `row`, returning its ID."[row :- ::data-apps.schema/data-app.update]@@ -91,49 +97,6 @@[data-app-id :- ms/PositiveInt](t2/select-one-fn :resource_collection_id :model/DataApp :id data-app-id))-(defn resource-collection-owned?- "Whether a data app owns the collection with `collection-id`."- [collection-id]- (t2/exists? :model/DataApp :resource_collection_id collection-id))--(defn data-app-by-entity-id- "The `:id`, `:entity_id`, and `:resource_collection_id` of the DataApp with `entity-id`, or nil."- [entity-id]- (t2/select-one [:model/DataApp :id :entity_id :resource_collection_id] :entity_id entity-id))--(defn active-table?- "Whether the table with `table-id` is active."- [table-id]- (some? (t2/select-one-pk :model/Table :id table-id :active true- {:from [(warehouse-schema-overlay/table-query {:user-settings? false})]})))--(defn active-field?- "Whether the field with `field-id` is active."- [field-id]- (some? (t2/select-one-pk :model/Field :id field-id :active true- {:from [(warehouse-schema-overlay/field-query {:user-settings? false})]})))--(defn collections-by-entity-ids- "The `:id`, `:entity_id` and `:namespace` of the collections with `entity-ids`."- [entity-ids]- (if (seq entity-ids)- (t2/query {:select [:id :entity_id :namespace] :from [:collection] :where [:in :entity_id entity-ids]})- []))--(defn cards-by-entity-ids- "The `:entity_id` and `:collection_id` of the cards with `entity-ids`."- [entity-ids]- (if (seq entity-ids)- (t2/query {:select [:entity_id :collection_id] :from [:report_card] :where [:in :entity_id entity-ids]})- []))--(defn actions-by-entity-ids- "The `:entity_id` and `:collection_id` of the actions with `entity-ids`."- [entity-ids]- (if (seq entity-ids)- (t2/select [:model/Action :entity_id :collection_id] :entity_id [:in entity-ids])- []))-(defn collection-card-ids"The IDs of the cards in the collection with `collection-id`."[collection-id]diff --git a/enterprise/backend/src/metabase_enterprise/data_apps/models/data_app.clj b/enterprise/backend/src/metabase_enterprise/data_apps/models/data_app.cljindex a9baf56fc90..71a509bae6c 100644--- a/enterprise/backend/src/metabase_enterprise/data_apps/models/data_app.clj+++ b/enterprise/backend/src/metabase_enterprise/data_apps/models/data_app.clj@@ -72,11 +72,29 @@(mu/validate-throw schema)with-bundle-hash))+(defn- check-resource-collection+ "Throws unless the Collection with `collection-id` can be the resource collection of the data app `app-id`: a+ top-level collection of data apps, not archived, official, typed or the sample, that no other app has; remote sync may+ sync it."+ [collection-id app-id]+ (let [collection (data-apps.db/resource-collection collection-id)]+ (when-not (and collection+ (= "data-apps" (some-> (:namespace collection) name))+ (= "/" (:location collection))+ (not-any? collection [:personal_owner_id :authority_level :type :archive_operation_id])+ (not-any? collection [:archived :is_sample]))+ (throw (ex-info (tru "A data app''s collection must be a top-level collection of data apps that isn''t archived or official. Give the app a collection of its own.")+ {:status-code 400, :collection-id collection-id})))+ (when (data-apps.db/other-app-has-collection? collection-id app-id)+ (throw (ex-info (tru "This collection already belongs to another data app. Give the app a collection of its own.")+ {:status-code 400, :collection-id collection-id})))))+(t2/define-before-insert :model/DataApp[data-app];; Every app owns a resource collection from its first moment: one it is given (an import names the collection;; its manifest references) or one created here, so the column is never null.(let [row (prepare ::data-apps.schema/data-app.insert data-app)]+ (some-> (:resource_collection_id row) (check-resource-collection nil))(cond-> row(nil? (:resource_collection_id row))(assoc :resource_collection_id (:id (data-app.resources/create-resource-collection! row))))))@@ -90,6 +108,7 @@(some? (:resource_collection_id (t2/original data-app))))(throw (ex-info (tru "A data app''s resource collection cannot be changed."){:status-code 400, :data-app-id (:id data-app)})))+ (some-> (:resource_collection_id changes) (check-resource-collection (:id data-app)))(merge data-app (some->> changes (prepare ::data-apps.schema/data-app.update)))));; Reads always see `allowed_hosts` as a vector, never nil — a row synced before@@ -222,7 +241,8 @@(data-apps.db/resource-collection-ids))(defenterprise data-app-collection?- "Whether the Collection with `collection-id` is a data app's resource collection."+ "Whether the Collection with `collection-id` is in the data-apps namespace, which holds only data apps' collections;+ asked of the namespace, not of the apps, since a load may write a collection's content before the app that owns it.":feature :none[collection-id]- (data-apps.db/resource-collection? collection-id))+ (data-apps.db/data-apps-namespace-collection? collection-id))diff --git a/enterprise/backend/src/metabase_enterprise/data_apps/resource_validation.clj b/enterprise/backend/src/metabase_enterprise/data_apps/resource_validation.cljdeleted file mode 100644index c0a19e35e90..00000000000--- a/enterprise/backend/src/metabase_enterprise/data_apps/resource_validation.clj+++ /dev/null@@ -1,431 +0,0 @@-(ns metabase-enterprise.data-apps.resource-validation- "What a data app's resources may hold. An app's resources are its collection, the one its `data_app.yaml` names as- `collection`, and the cards and actions in it, all ordinary entity files under `collections/`. A load trusts what it- reads: it updates whatever row carries an entity ID and resolves references to any local entity. These checks run- on the ingested files first, so an app's resources can only be its own collection, in the `data-apps` namespace,- and, in it, questions, metrics, and query actions that belong to no model, referencing nothing else of Metabase's- but what already exists, apart from the databases, tables and fields that a load stubs as it does for any card."- (:require- [clojure.string :as str]- [clojure.walk :as walk]- [metabase-enterprise.data-apps.db :as data-apps.db]- [metabase.models.db :as models.db]- [metabase.models.serialization :as serdes]- [metabase.util.i18n :refer [tru]]))--(set! *warn-on-reflection* true)--(def ^:private external-dependency-models- "Models a resource may reference outside the app. A snippet, segment or measure must already exist or come with the- same pull; a database, table or field is never a dependency, as a load stubs one that is missing."- #{"Database" "Table" "Field" "NativeQuerySnippet" "Segment" "Measure"})--(def ^:private card-types #{"question" "metric"})--(defn- leaf [path]- (last path))--(defn- problem [file message]- {:file file :message message})--(defn- identity-problems [{:keys [path model entity]}]- (let [meta-path (:serdes/meta entity)- {meta-model :model meta-id :id} (leaf meta-path)]- (when-not (and (= 1 (count meta-path))- (= model meta-model)- (serdes/entity-id? (:entity_id entity))- (= meta-id (:entity_id entity)))- [(problem path (tru "{0} must hold a single {1} whose serdes/meta ID is its entity_id." path model))])))--(defn- creator-problems- "A load creates the user a `creator_id` names when it has to, but can't save a card or action without one."- [{:keys [path entity]}]- (when (nil? (:creator_id entity))- [(problem path (tru "{0} must name its creator in creator_id." path))]))--(defn- public-problems [{:keys [path entity]}]- (when (or (some entity [:public_uuid :made_public_by_id :embedding_params :embedding_type])- (:enable_embedding entity))- [(problem path (tru "{0} must not be public or embedded." path))]))--(defn- type-name [entity]- (let [t (:type entity)]- (when (or (string? t) (keyword? t))- (name t))))--(defn- action-children-problems- "Serdes loads an action's implicit and query rows whatever its type, so a query action's file must carry exactly- its query row."- [{:keys [path entity]}]- (let [counts (update-vals (select-keys entity [:implicit :query]) count)]- (when (not= {:query 1} (into {} (remove (comp zero? val)) counts))- [(problem path (tru "{0} must carry exactly one query, and no implicit action." path))])))--(defn- parameter-source-problems- "An action's parameters can take their values from a card, which its dependencies don't include."- [{:keys [path entity]}]- (when (some (comp :card_id :values_source_config) (:parameters entity))- [(problem path (tru "{0} must not take parameter values from a card." path))]))--(defn- model-problems [{:keys [path model entity] :as file}]- (case model- "Collection"- (concat- (when (not= "data-apps" (some-> (:namespace entity) name))- [(problem path (tru "{0} must be in the data-apps collection namespace." path))])- (when (or (some entity [:parent_id :personal_owner_id :authority_level :type :archive_operation_id])- (:is_remote_synced entity)- (:is_sample entity)- (:archived entity))- [(problem path (tru "{0} must be a root collection that is not remote-synced or archived." path))]))-- "Card"- (concat- (when-not (card-types (type-name entity))- [(problem path (tru "{0} must be a question or metric." path))])- (when-not (and (map? (:dataset_query entity)) (some? (:database (:dataset_query entity))))- [(problem path (tru "{0} must hold a query." path))])- (when (:archived entity)- [(problem path (tru "{0} must not be archived." path))])- (when (some entity [:dashboard_id :document_id])- [(problem path (tru "{0} must not belong to a dashboard or document." path))])- (creator-problems file)- (public-problems file))-- "Action"- (concat- ;; a data app runs only query actions that belong to no model, the ones the typed schema lists- (when (not= "query" (type-name entity))- [(problem path (tru "{0} must be a query action." path))])- (when (some? (:model_id entity))- [(problem path (tru "{0} must belong to no model." path))])- (when (:archived entity)- [(problem path (tru "{0} must not be archived." path))])- (action-children-problems file)- (parameter-source-problems file)- (creator-problems file)- (public-problems file))))--(defn- dependencies- "The serdes dependencies of the entity in `file`, or nil with a problem when they can't be read."- [{:keys [path entity]}]- (try- [(serdes/deserialization-dependencies entity) nil]- (catch Exception e- [nil (problem path (tru "{0} is malformed: {1}" path (ex-message e)))])))--(defn- dependency-problems- [collection-entity-id card-entity-ids {:keys [path] :as file}]- (let [[deps malformed] (dependencies file)]- (if malformed- [malformed]- (for [dependency deps- :let [{:keys [model id]} (leaf dependency)]- :when (case model- "Collection" (not= id collection-entity-id)- "Card" (not (contains? card-entity-ids id))- (not (contains? external-dependency-models model)))]- (problem path (tru "{0} references {1} {2}, which is not one of the app''s resources." path model id))))))--(defn- numeric-reference-problems- "A serialized query names cards, tables, fields and snippets by entity ID or by path. A numeric ID names a row on one- instance only, and the dependency checks, which read entity IDs, don't see it."- [{:keys [path entity]}]- (let [numeric? (volatile! false)- ;; a card as a source table, in the older form- card-ref? (fn [x] (and (string? x) (re-matches #"card__\d+" x)))]- (walk/postwalk (fn [x]- (when (or (and (map? x)- (or (some #(integer? (get x %))- [:source-card :source-table :card-id :snippet-id :table-id :source-field :database])- (card-ref? (:source-table x))))- (and (vector? x)- (or (string? (first x)) (keyword? (first x)))- (contains? #{"field" "metric" "segment" "measure"} (name (first x)))- (some integer? (rest x))))- (vreset! numeric? true))- x)- (select-keys entity [:dataset_query :query]))- (when @numeric?- [(problem path (tru "{0} must not reference a card, table, field, snippet or database by numeric ID." path))])))--(defn- duplicate-problems [resources]- (for [[[model entity-id] files] (group-by (juxt :model (comp :entity_id :entity)) resources)- :when (< 1 (count files))]- (problem (:path (first files))- (tru "{0} {1} is defined by more than one file: {2}." model entity-id (str/join ", " (map :path files))))))--(defn- external-dependency-problems- "`defined` holds the `[model entity-id]` of each dependency that the same pull loads from outside `data_apps/`."- [defined resources]- (for [{:keys [path] :as file} resources- dependency (first (dependencies file))- :let [{:keys [model id]} (leaf dependency)]- :when (and (contains? external-dependency-models model)- (not (contains? defined [model id]))- (nil? (serdes/load-find-local dependency)))]- (problem path (tru "{0} references {1} {2}, which does not exist on this instance." path model id))))--(defn- portable-refs- "The portable table references (`[db schema table]`) and field references (`[db schema table field ...]`) that- `entity` makes, in each place where serialization reads one: a query's source table, a field clause in either form,- the source field of a field clause, a table template tag, and a column of the result metadata."- [entity]- (let [refs (volatile! #{})- names? (fn [x] (and (vector? x) (string? (first x)) (every? #(or (nil? %) (string? %)) x)))- table? (fn [x] (and (names? x) (= 3 (count x))))- field? (fn [x] (and (names? x) (< 3 (count x))))- add! (fn [kind x] (vswap! refs conj [kind x]))]- (walk/postwalk (fn [x]- (cond- (map? x)- (do- (doseq [k [:source-table :table-id :table_id]- :when (table? (get x k))]- (add! :table (get x k)))- (when (field? (:source-field x))- (add! :field (:source-field x)))- ;; a column of the result metadata names its field as `:id`- (when (and (contains? x :base_type) (field? (:id x)))- (add! :field (:id x))))-- (and (vector? x) (#{"field" :field} (first x)))- (doseq [part (rest x)- :when (field? part)]- (add! :field part)))- x)- (select-keys entity [:dataset_query :query :parameter_mappings :result_metadata]))- @refs))--(defn- table-and-field-warnings- "A warning for each table or field `file` references that this instance lacks or that is inactive, which the load- resolves as it does for any card, through a stub database and inactive placeholders that a sync later fills in."- [{:keys [path] :as file}]- (for [[kind [db-name schema table-name & field-names :as ref]] (sort-by second (portable-refs (:entity file)))- :let [table-id (some->> (models.db/database-id-by-name db-name)- (models.db/table-id-by-name table-name schema))- id (if (= kind :table)- table-id- (some-> table-id (models.db/field-pk-in-path (reverse field-names))))- label (if (= kind :table) "table" "field")- message (cond- (nil? id)- (tru "{0} references {1} {2}, which does not exist on this instance yet, so the app''s queries fail until it is synced."- path label (pr-str ref))-- (not (if (= kind :table) (data-apps.db/active-table? id) (data-apps.db/active-field? id)))- (tru "{0} references {1} {2}, which is inactive on this instance." path label (pr-str ref)))]- :when message]- (problem path message)))--(defn- ownership-problems- "Serdes would update any row carrying an entity ID a file names, so a file may only name what this app owns:- the collection its manifest names, if it exists, must be the collection the app has, or one of the namespace that- no app owns, and existing cards and actions must be in it."- [app-entity-id manifest-path collection-entity-id resources]- (let [app (data-apps.db/data-app-by-entity-id app-entity-id)- app-collection-id (:resource_collection_id app)- collections (data-apps.db/collections-by-entity-ids [collection-entity-id])- ;; a collection on the instance that no app owns, or this app owns, may be the app's; another app's may not- owned? (fn [collection-id]- (or (= app-collection-id collection-id)- (not (data-apps.db/resource-collection-owned? collection-id))))- ;; a collection of the namespace that no app owns is the app's to claim with what it holds: what an earlier- ;; pull loaded into it before the app itself failed to load- claimable-id (when (nil? app-collection-id)- (some (fn [{:keys [id] collection-namespace :namespace}]- (when (and (= :data-apps (keyword collection-namespace))- (not (data-apps.db/resource-collection-owned? id)))- id))- collections))- in-collection? (fn [collection-id]- (or (and (some? app-collection-id) (= app-collection-id collection-id))- (and (some? claimable-id) (= claimable-id collection-id))))- entity-ids-of (fn [model]- (into [] (comp (filter (comp #{model} :model)) (map (comp :entity_id :entity))) resources))- file-of (fn [model entity-id]- (some #(when (and (= model (:model %)) (= entity-id (:entity_id (:entity %)))) (:path %))- resources))]- (concat- ;; the app's hooks refuse a change of collection, but only after the load has moved what it reached first- (when (and (some? app-collection-id) (not-any? #(= app-collection-id (:id %)) collections))- [(problem manifest-path- (tru "{0} names collection {1}, but the app already has a collection, and a data app''s collection cannot be changed."- manifest-path collection-entity-id))])- (for [{:keys [id entity_id] collection-namespace :namespace} collections- :let [path (or (file-of "Collection" entity_id) manifest-path)- message (cond- (not= :data-apps (keyword collection-namespace))- (tru "{0} defines collection {1}, which already exists outside the data-apps namespace, so it can''t become a data app''s collection. Give the app a collection of its own: a new entity ID in data_app.yaml and in the collection''s file."- path entity_id)-- (not (owned? id))- (tru "{0} defines collection {1}, which already exists and is another data app''s collection. Give the app a collection of its own: a new entity ID in data_app.yaml and in the collection''s file."- path entity_id))]- :when message]- (problem path message))- (for [[model rows] [["Card" (data-apps.db/cards-by-entity-ids (entity-ids-of "Card"))]- ["Action" (data-apps.db/actions-by-entity-ids (entity-ids-of "Action"))]]- {:keys [entity_id collection_id]} rows- :when (not (in-collection? collection_id))- :let [path (file-of model entity_id)]]- (problem path- (tru "{0} defines {1} {2}, which already exists outside this data app''s collection, so the app can''t load it. Move it back if it belongs to this app."- path model entity_id))))))--(defn- model-of [entity]- (:model (last (:serdes/meta entity))))--(defn- app-resources- "Among `files`, the collection with `collection-entity-id` and the cards and actions in it, each with its `:model`."- [collection-entity-id files]- (for [{:keys [entity] :as file} files- :let [model (model-of entity)]- :when (or (and (= "Collection" model) (= collection-entity-id (:entity_id entity)))- (and (contains? #{"Card" "Action"} model)- (= collection-entity-id (:collection_id entity))))]- (assoc file :model model)))--(defn- app-problems- "The problems of one app: its manifest file, and among `files` its collection and the cards and actions in it."- [defined manifest files]- (let [manifest-problems (identity-problems (assoc manifest :model "DataApp"))- collection-entity-id (-> manifest :entity :collection)- app-entity-id (-> manifest :entity :entity_id)- resources (app-resources collection-entity-id files)- collection-files (filter (comp #{"Collection"} :model) resources)]- (cond- (seq manifest-problems)- manifest-problems-- (nil? collection-entity-id)- [(problem (:path manifest) (tru "{0} must name the app''s resource collection as `collection`." (:path manifest)))]-- (empty? collection-files)- [(problem (:path manifest)- (tru "The collection {0} that {1} names is not in the repository. Write it under collections/data_apps/ and commit it."- collection-entity-id (:path manifest)))]-- :else- (let [cards (filter (comp #{"Card"} :model) resources)- card-entity-ids (into #{} (map (comp :entity_id :entity)) cards)- structural (concat (duplicate-problems resources)- (mapcat identity-problems resources))]- (if (seq structural)- structural- (concat- (mapcat model-problems resources)- (mapcat numeric-reference-problems resources)- (mapcat (partial dependency-problems collection-entity-id card-entity-ids) resources)- (ownership-problems app-entity-id (:path manifest) collection-entity-id resources)- (external-dependency-problems defined resources)))))))--(defn- shared-collection-problems- "Two apps can't name one collection: only one of them would own it."- [manifests]- (for [[collection-entity-id named-by] (group-by (comp :collection :entity) manifests)- :when (and collection-entity-id (< 1 (count named-by)))- {:keys [path]} named-by]- (problem path (tru "{0} names collection {1}, which another data app also names." path collection-entity-id))))--(defn- shared-resource-problems- "Two apps can't define one card or action: a load would give it to whichever file loads last."- [manifests files]- (let [resources (for [{:keys [entity path]} manifests- resource (app-resources (:collection entity) files)]- (assoc resource :manifest path))]- (for [[[model entity-id] defined-by] (group-by (juxt :model (comp :entity_id :entity)) resources)- :when (< 1 (count (into #{} (map :manifest) defined-by)))- ;; each app that names a collection finds every file of it, so a file can be here once per app- :let [paths (distinct (map :path defined-by))]]- (problem (first paths) (tru "{0} {1} is defined by more than one data app: {2}." model entity-id (str/join ", " paths))))))--(defn- shared-entity-id-problems- "Two manifests can't carry one entity ID: a load keeps one app, and the other's collection is left with no owner."- [manifests]- (for [[entity-id carried-by] (group-by (comp :entity_id :entity) manifests)- :when (and entity-id (< 1 (count carried-by)))- {:keys [path]} carried-by]- (problem path (tru "{0} has the entity ID {1}, which another data app also has." path entity-id))))--(defn- shared-slug-problems- "Two manifests can't carry one slug: a load keeps the first app and refuses the second after it has started."- [manifests]- (for [[slug carried-by] (group-by (comp :slug :entity) manifests)- :when (and slug (< 1 (count carried-by)))- {:keys [path]} carried-by]- (problem path (tru "{0} has the slug {1}, which another data app also has." path slug))))--(defn- taken-slug-problems- "An app made on the instance keeps its slug, and a load would refuse the repository's app only after its collection- and cards had loaded."- [manifests]- (for [{:keys [path entity]} manifests- :let [slug (:slug entity)- taken-by (when (string? slug) (data-apps.db/data-app-entity-id-named slug))]- :when (and taken-by (not= taken-by (:entity_id entity)))]- (problem path (tru "{0} has the slug {1}, which a data app made on this instance already has. Delete that app, or give the app in the repository another slug."- path slug))))--(defn- child-collection-problems- "A data app's collection holds no collections, and a load would refuse one only after it had started."- [manifests files]- (let [app-collections (into #{} (keep (comp :collection :entity)) manifests)]- (for [{:keys [path entity]} files- :when (and (= "Collection" (model-of entity)) (contains? app-collections (:parent_id entity)))]- (problem path (tru "{0} is a collection inside a data app''s collection, which can''t hold one." path)))))--(defn- other-content-problems- "A data app's collection holds cards and actions only, and a load would refuse anything else only after it had- started."- [manifests files]- (let [app-collections (into #{} (keep (comp :collection :entity)) manifests)]- (for [{:keys [path entity]} files- :when (and (contains? app-collections (:collection_id entity))- (not (contains? #{"Card" "Action"} (model-of entity))))]- (problem path (tru "{0} is in a data app''s collection, which holds only questions, metrics and query actions." path)))))--(defn- defined-dependencies- "The `[model entity-id]` of each snippet, segment and measure that `files` load: a resource that names one counts- it as present, since the same pull brings it."- [files]- (into #{}- (comp (map (comp (juxt :model :id) last :serdes/meta :entity))- (filter (comp #{"NativeQuerySnippet" "Segment" "Measure"} first)))- files))--(defn- manifests-among- "The manifest files among `files`: the entities that say they are a DataApp, and the files at a manifest's path too,- as one that doesn't say what it is would be skipped by the load, and the app deleted as no longer in the repository."- [files]- (filter #(or (= "DataApp" (model-of (:entity %)))- (re-matches #"data_apps/[^/]+/data_app\.yaml" (:path %)))- files))--(defn warnings- "What a pull logs about the data apps among the entity files `files` (see [[problems]]), each as `{:file :message}`:- what loads, but may not run as the author meant it."- [files]- (for [{:keys [entity]} (manifests-among files)- resource (app-resources (:collection entity) files)- warning (table-and-field-warnings resource)]- warning))--(defn problems- "The problems with the data apps among the entity files `files` (`{:path :entity}`, every entity file of the- snapshot), each once, as `{:file :message}` with a message that names the file. An app whose resources have a- problem can't be loaded as the author meant it, so an import that sees one fails listing the messages."- [files]- (let [manifests (manifests-among files)- defined (defined-dependencies files)]- (distinct- (concat- (shared-entity-id-problems manifests)- (shared-slug-problems manifests)- (taken-slug-problems manifests)- (shared-collection-problems manifests)- (shared-resource-problems manifests files)- (child-collection-problems manifests files)- (other-content-problems manifests files)- ;; apps that name one collection each find the problems of its files- (mapcat #(app-problems defined % files) manifests)))))diff --git a/enterprise/backend/src/metabase_enterprise/remote_sync/impl.clj b/enterprise/backend/src/metabase_enterprise/remote_sync/impl.cljindex b3476651eb9..e557c74a344 100644--- a/enterprise/backend/src/metabase_enterprise/remote_sync/impl.clj+++ b/enterprise/backend/src/metabase_enterprise/remote_sync/impl.clj@@ -147,10 +147,6 @@(instance? java.net.UnknownHostException (ex-cause e)))"Network error: Unable to reach git repository host"- ;; the validator names a file, whose path may hold any word the matches below look for- (= (:error (ex-data e)) :metabase-enterprise.remote-sync.source.ingestable/invalid-data-app-files)- (str "Failed to reload from git repository. " message)-(str/includes? message "Authentication failed")"Authentication failed: Please check your git credentials"@@ -650,10 +646,6 @@(try(let [snapshot-version (source.p/version snapshot)last-imported-version (remote-sync.task/last-version)- ;; before anything is read for loading, the files of each data app's collection are checked; a pull of- ;; the commit already imported loads nothing, so there is nothing to check- _ (when (or force? merge? (not= last-imported-version snapshot-version))- (source.ingestable/check-data-app-files! snapshot))first-import? (nil? last-imported-version);; force-deletion? defaults to force? when a caller doesn't pass it.force-deletion? (if (nil? force-deletion?) force? force-deletion?)@@ -827,8 +819,7 @@:conflicts labels:merge-summary summary:message "Export blocked: the same content was changed both locally and on the remote branch."})- (let [_ (source.ingestable/check-data-app-files! (source/specs->snapshot merged))- [_ version] (commit-staged! snapshot message+ (let [[_ version] (commit-staged! snapshot message(fn [commit](source/replace-managed-files! commit snapshot) ; merged set replaces the managed files wholesale(run! #(source.p/stage-upsert! commit %) merged)))diff --git a/enterprise/backend/src/metabase_enterprise/remote_sync/source/ingestable.clj b/enterprise/backend/src/metabase_enterprise/remote_sync/source/ingestable.cljindex 1940b937d29..d3b8edf2ec5 100644--- a/enterprise/backend/src/metabase_enterprise/remote_sync/source/ingestable.clj+++ b/enterprise/backend/src/metabase_enterprise/remote_sync/source/ingestable.clj@@ -1,7 +1,6 @@(ns metabase-enterprise.remote-sync.source.ingestable(:require[clojure.string :as str]- [metabase-enterprise.data-apps.core :as data-apps][metabase-enterprise.remote-sync.source.protocol :as source.p][metabase-enterprise.serialization.core :as serialization][metabase.models.serialization :as serdes]@@ -33,28 +32,6 @@(serdes/restore-path(serialization/read-timestamps (yaml/parse-string file-content {:key-fn serialization/parse-key}))))-(defn check-data-app-files!- "Throws, naming each file, when a data app's files in `snapshot` (its manifest, its collection, and what the- collection holds) carry what a load can't take as the author meant it. Serialization trusts what it reads, so this- is what keeps an app's resources to its own collection; it runs on the whole snapshot before any import, since an- incremental import ingests only the changed files. A file that doesn't parse is left to ingestion to report, but a- manifest that doesn't is kept, so that its own problem names it rather than the app being deleted as no longer in- the repository."- [snapshot]- (let [files (vec (for [path (source.p/list-files snapshot)- :when (serialization/entity-file-path? path)- :let [entity (try- (ingest-content (source.p/read-file snapshot path))- (catch Exception _ nil))]- :when (or entity (re-matches #"data_apps/[^/]+/data_app\.yaml" path))]- {:path path :entity entity}))- problems (data-apps/problems files)]- (when (seq problems)- (throw (ex-info (str/join "\n" (cons "Invalid data app files:" (map #(str "- " (:message %)) problems)))- {:files (mapv :file problems) :error ::invalid-data-app-files})))- (doseq [{:keys [file message]} (data-apps/warnings files)]- (log/warnf "Data app file %s: %s" file message))))-(defn- ingest-all"Returns {:entities {stripped-hierarchy {:content <yaml-string> :path <repo-path>}}, :errors [Exception...]}.The repo `:path` is the actual file the entity was read from (including any dedup suffix), so callersdiff --git a/enterprise/backend/src/metabase_enterprise/transform_testing/api.clj b/enterprise/backend/src/metabase_enterprise/transform_testing/api.cljindex 93b806a621a..73c9d38f5a5 100644--- a/enterprise/backend/src/metabase_enterprise/transform_testing/api.clj+++ b/enterprise/backend/src/metabase_enterprise/transform_testing/api.clj@@ -8,7 +8,12 @@[metabase.api.macros :as api.macros][metabase.api.routes.common :refer [+auth]][metabase.models.interface :as mi]- [metabase.util.malli.schema :as ms]))+ [metabase.query-processor.parameters.dates :as params.dates]+ [metabase.request.core :as request]+ [metabase.util.date-2 :as u.date]+ [metabase.util.i18n :refer [tru]]+ [metabase.util.malli.schema :as ms]+ [toucan2.core :as t2]))(set! *warn-on-reflection* true)@@ -29,19 +34,21 @@:error-code (transform-testing.errors/code error-type))))(throw e)))))-(api.macros/defendpoint :get "/" :- [:sequential ::transform-testing.schema/transform-test]- "List the transform tests, optionally only those of one transform."+(api.macros/defendpoint :get "/" :- [:sequential ::transform-testing.schema/transform-test.response]+ "List the transform tests with their newest runs, optionally only those of one transform."[_route-params{:keys [transform-id]} :- [:map {:closed true}[:transform-id {:optional true} [:maybe ms/PositiveInt]]]](api/check-data-studio-access)- (filter mi/can-read? (transform-testing.db/transform-tests {:transform-id transform-id})))+ (-> (filter mi/can-read? (transform-testing.db/transform-tests {:transform-id transform-id}))+ (t2/hydrate :last_run)))-(api.macros/defendpoint :get "/:id" :- ::transform-testing.schema/transform-test- "Get a transform test."+(api.macros/defendpoint :get "/:id" :- ::transform-testing.schema/transform-test.response+ "Get a transform test with its newest run."[{:keys [id]} :- [:map {:closed true}[:id ms/PositiveInt]]]- (api/read-check (transform-testing.db/transform-test id)))+ (-> (api/read-check (transform-testing.db/transform-test id))+ (t2/hydrate :last_run)))(api.macros/defendpoint :post "/" :- ::transform-testing.schema/transform-test"Create a transform test."@@ -76,6 +83,42 @@(transform-testing.db/delete-transform-test! id)nil)+(defn- timestamp-range+ "The `[start end]` instants of the date filter `date-string`, or nil when it is nil."+ [date-string]+ (when date-string+ (let [{:keys [start end]} (try+ (params.dates/date-string->range date-string {:inclusive-end? false})+ (catch Exception e+ (throw (ex-info (tru "Failed to parse datetime value: {0}" date-string)+ {:status-code 400}+ e))))]+ [(some-> start u.date/parse) (some-> end u.date/parse)])))++(api.macros/defendpoint :get "/:id/run" :- ::transform-testing.schema/transform-test-runs.response+ "List the runs of a transform test, newest first."+ [{:keys [id]} :- [:map {:closed true}+ [:id ms/PositiveInt]]+ {:keys [statuses start-time end-time]} :- [:map {:closed true}+ [:statuses {:optional true} [:maybe (ms/QueryVectorOf ::transform-testing.schema/run-status)]]+ [:start-time {:optional true} [:maybe ms/NonBlankString]]+ [:end-time {:optional true} [:maybe ms/NonBlankString]]]]+ (api/read-check (transform-testing.db/transform-test id))+ (let [[started-at-start started-at-end] (timestamp-range start-time)+ [ended-at-start ended-at-end] (timestamp-range end-time)+ filters {:transform-test-id id+ :statuses statuses+ :started-at-start started-at-start+ :started-at-end started-at-end+ :ended-at-start ended-at-start+ :ended-at-end ended-at-end}+ limit (or (request/limit) 20)+ offset (or (request/offset) 0)]+ {:data (t2/hydrate (transform-testing.db/transform-test-runs filters limit offset) :initiated_by_user)+ :limit limit+ :offset offset+ :total (transform-testing.db/transform-test-run-count filters)}))+(api.macros/defendpoint :post "/:id/run" :- ::transform-testing.schema/run-result"Run a transform test.diff --git a/enterprise/backend/src/metabase_enterprise/transform_testing/db.clj b/enterprise/backend/src/metabase_enterprise/transform_testing/db.cljindex f4ab758421b..0a5e47a4c27 100644--- a/enterprise/backend/src/metabase_enterprise/transform_testing/db.clj+++ b/enterprise/backend/src/metabase_enterprise/transform_testing/db.clj@@ -37,6 +37,56 @@:initiated_by initiated-by:status :started}))+(def ^:private RunFilters+ [:map {:closed true}+ [:transform-test-id ms/PositiveInt]+ [:statuses {:optional true} [:maybe [:sequential ::transform-testing.schema/run-status]]]+ [:started-at-start {:optional true} [:maybe ms/TemporalInstant]]+ [:started-at-end {:optional true} [:maybe ms/TemporalInstant]]+ [:ended-at-start {:optional true} [:maybe ms/TemporalInstant]]+ [:ended-at-end {:optional true} [:maybe ms/TemporalInstant]]])++(defn- run-filter-clause+ [{:keys [transform-test-id statuses started-at-start started-at-end ended-at-start ended-at-end]}]+ (cond-> [:and [:= :transform_test_id transform-test-id]]+ (seq statuses) (conj [:in :status (map name statuses)])+ started-at-start (conj [:>= :start_time started-at-start])+ started-at-end (conj [:< :start_time started-at-end])+ ended-at-start (conj [:>= :end_time ended-at-start])+ ended-at-end (conj [:< :end_time ended-at-end])))++(mu/defn transform-test-runs :- [:sequential ::transform-testing.schema/transform-test-run]+ "A page of the TransformTestRuns matching `filters`, newest first."+ [filters :- RunFilters+ limit :- ms/PositiveInt+ offset :- ms/IntGreaterThanOrEqualToZero]+ (t2/select :model/TransformTestRun {:where (run-filter-clause filters)+ :order-by [[:start_time :desc] [:id :desc]]+ :limit limit+ :offset offset}))++(mu/defn transform-test-run-count :- :int+ "The number of TransformTestRuns matching `filters`."+ [filters :- RunFilters]+ (t2/count :model/TransformTestRun {:where (run-filter-clause filters)}))++(mu/defn latest-transform-test-runs :- [:sequential ::transform-testing.schema/transform-test-run]+ "The newest TransformTestRun of each of the TransformTests with `transform-test-ids`."+ [transform-test-ids :- [:set ms/PositiveInt]]+ (t2/select :model/TransformTestRun+ {:where [:and+ [:in :transform_test_run.transform_test_id transform-test-ids]+ [:not [:exists ^:allow-subquery {:select [1]+ :from [[:transform_test_run :newer]]+ :where [:and+ [:= :newer.transform_test_id :transform_test_run.transform_test_id]+ [:> :newer.id :transform_test_run.id]]}]]]}))++(mu/defn users-by-id+ "A map of User id to the id, email, and name of the Users with `user-ids`."+ [user-ids :- [:set ::lib.schema.id/user]]+ (t2/select-pk->fn identity [:model/User :id :email :first_name :last_name] :id [:in user-ids]))+(mu/defn finish-started-transform-test-run!"Set `status` and the end time of TransformTestRun `run-id` if it is still started."[run-id :- ms/PositiveIntdiff --git a/enterprise/backend/src/metabase_enterprise/transform_testing/models.clj b/enterprise/backend/src/metabase_enterprise/transform_testing/models.cljindex 99ce43e83d3..cd0f1fd9f79 100644--- a/enterprise/backend/src/metabase_enterprise/transform_testing/models.clj+++ b/enterprise/backend/src/metabase_enterprise/transform_testing/models.clj@@ -35,6 +35,17 @@{:inputs (json-column ::transform-testing.schema/inputs):expectations (json-column ::transform-testing.schema/expectations)})+(methodical/defmethod t2/batched-hydrate [:model/TransformTest :last_run]+ "Add the newest run, or nil, to each transform test."+ [_model _k transform-tests]+ (if-not (seq transform-tests)+ transform-tests+ (let [id->run (into {}+ (map (juxt :transform_test_id identity))+ (transform-testing.db/latest-transform-test-runs (into #{} (map :id) transform-tests)))]+ (for [transform-test transform-tests]+ (assoc transform-test :last_run (get id->run (:id transform-test)))))))+(defmethod audit-app/model-details :model/TransformTest[transform-test _event-type](select-keys transform-test [:transform_id :name :description]))diff --git a/enterprise/backend/src/metabase_enterprise/transform_testing/models/transform_test_run.clj b/enterprise/backend/src/metabase_enterprise/transform_testing/models/transform_test_run.cljindex f80059e6dea..2341b932295 100644--- a/enterprise/backend/src/metabase_enterprise/transform_testing/models/transform_test_run.clj+++ b/enterprise/backend/src/metabase_enterprise/transform_testing/models/transform_test_run.clj@@ -1,5 +1,6 @@(ns metabase-enterprise.transform-testing.models.transform-test-run(:require+ [metabase-enterprise.transform-testing.db :as transform-testing.db][metabase.audit-app.core :as audit-app][metabase.models.interface :as mi][methodical.core :as methodical]@@ -15,3 +16,11 @@(t2/deftransforms :model/TransformTestRun{:status mi/transform-keyword})++(methodical/defmethod t2/batched-hydrate [:model/TransformTestRun :initiated_by_user]+ "Add the user who started each run, or nil."+ [_model _k runs]+ (let [user-ids (into #{} (keep :initiated_by) runs)+ id->user (when (seq user-ids) (transform-testing.db/users-by-id user-ids))]+ (for [run runs]+ (assoc run :initiated_by_user (get id->user (:initiated_by run))))))diff --git a/enterprise/backend/src/metabase_enterprise/transform_testing/schema.clj b/enterprise/backend/src/metabase_enterprise/transform_testing/schema.cljindex c02654663c0..99f76e3ccf8 100644--- a/enterprise/backend/src/metabase_enterprise/transform_testing/schema.clj+++ b/enterprise/backend/src/metabase_enterprise/transform_testing/schema.clj@@ -185,6 +185,37 @@[:status ::run-status][:last_heartbeat ms/TemporalInstant]])+(mr/def ::user+ "The user who started a run."+ [:map {:closed true}+ [:id ::lib.schema.id/user]+ [:email :string]+ [:first_name [:maybe :string]]+ [:last_name [:maybe :string]]+ [:common_name {:optional true} [:maybe :string]]])++(mr/def ::transform-test-run.response+ "A transform test run as the API returns it, with the user who started it."+ [:merge+ ::transform-test-run+ [:map {:closed true}+ [:initiated_by_user [:maybe ::user]]]])++(mr/def ::transform-test-runs.response+ "A page of transform test runs."+ [:map {:closed true}+ [:data [:sequential ::transform-test-run.response]]+ [:limit pos-int?]+ [:offset :int]+ [:total :int]])++(mr/def ::transform-test.response+ "A transform test as the read endpoints return it, with its newest run."+ [:merge+ ::transform-test+ [:map {:closed true}+ [:last_run [:maybe ::transform-test-run]]]])+(mr/def ::status"The outcome of a transform test run, or of one of its expectations.diff --git a/enterprise/backend/test/metabase_enterprise/data_apps/api_test.clj b/enterprise/backend/test/metabase_enterprise/data_apps/api_test.cljindex 718d66a493f..01d1f7324cd 100644--- a/enterprise/backend/test/metabase_enterprise/data_apps/api_test.clj+++ b/enterprise/backend/test/metabase_enterprise/data_apps/api_test.clj@@ -6,6 +6,7 @@[metabase-enterprise.data-apps.config :as data-app.config][metabase-enterprise.data-apps.group-access :as group-access][metabase-enterprise.data-apps.resources :as data-app.resources]+ [metabase-enterprise.data-apps.test-util :as data-apps.tu][metabase.actions.core :as actions][metabase.lib.core :as lib][metabase.lib.metadata :as lib.metadata]@@ -323,14 +324,15 @@(mt/with-temp [:model/PermissionsGroup group {}](let [app (t2/select-one :model/DataApp :name "demo"){collection-id :resource_collection_id} (data-app.resources/ensure-resources! app)]- (mt/with-temp [:model/Card {card-id :id} {:collection_id collection-id}]- (group-access/add-groups! app [(:id group)])- (mt/user-http-request :crowberto :delete 204 "ee/apps/demo")- (is (not (t2/exists? :model/DataApp :id (:id app))))- (is (not (t2/exists? :model/Collection :id collection-id)))- (is (not (t2/exists? :model/Card :id card-id)))- (is (empty? (t2/select :model/DataAppGroupAssignment :data_app_id (:id app))))- (is (t2/exists? :model/PermissionsGroup :id (:id group)))))))))+ (data-apps.tu/with-published-tables! [(mt/id :venues)]+ (mt/with-temp [:model/Card {card-id :id} {:collection_id collection-id :dataset_query (data-apps.tu/venues-query)}]+ (group-access/add-groups! app [(:id group)])+ (mt/user-http-request :crowberto :delete 204 "ee/apps/demo")+ (is (not (t2/exists? :model/DataApp :id (:id app))))+ (is (not (t2/exists? :model/Collection :id collection-id)))+ (is (not (t2/exists? :model/Card :id card-id)))+ (is (empty? (t2/select :model/DataAppGroupAssignment :data_app_id (:id app))))+ (is (t2/exists? :model/PermissionsGroup :id (:id group))))))))));;; ----------------------------------------------------- API -----------------------------------------------------@@ -447,79 +449,81 @@(deftest admins-write-the-resource-collection-through-the-api-test(mt/with-premium-features #{:data-apps}- (mt/with-actions-enabled- (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup :model/Card :model/Action]- (let [{collection-id :resource_collection_id} (mt/user-http-request :crowberto :post 200 "ee/apps" {:name "demo"})- query (lib/query (mt/metadata-provider) (lib.metadata/table (mt/metadata-provider) (mt/id :venues)))]- (testing "an admin creates a question in the app's collection"- (is (=? {:collection_id collection-id}- (mt/user-http-request :crowberto :post 200 "card" {:name "Venues"- :collection_id collection-id- :display "table"- :visualization_settings {}- :dataset_query query}))))- (testing "an admin creates an action in the app's collection"- (is (=? {:collection_id collection-id}- (mt/user-http-request :crowberto :post 200 "action"- {:name "Rename venues"- :type "query"- :database_id (mt/id)- :collection_id collection-id- :dataset_query (lib/native-query (mt/metadata-provider)- "UPDATE venues SET name = {{name}}")- :parameters [{:id "name" :slug "name" :type "string/="- :target [:variable [:template-tag "name"]]}]}))))- (testing "nobody else writes it"- (mt/user-http-request :rasta :post 403 "card" {:name "Mine"- :collection_id collection-id- :display "table"- :visualization_settings {}- :dataset_query query})))))))+ (data-apps.tu/with-published-tables! [(mt/id :venues)]+ (mt/with-actions-enabled+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup :model/Card :model/Action]+ (let [{collection-id :resource_collection_id} (mt/user-http-request :crowberto :post 200 "ee/apps" {:name "demo"})+ query (lib/query (mt/metadata-provider) (lib.metadata/table (mt/metadata-provider) (mt/id :venues)))]+ (testing "an admin creates a question in the app's collection"+ (is (=? {:collection_id collection-id}+ (mt/user-http-request :crowberto :post 200 "card" {:name "Venues"+ :collection_id collection-id+ :display "table"+ :visualization_settings {}+ :dataset_query query}))))+ (testing "an admin creates an action in the app's collection"+ (is (=? {:collection_id collection-id}+ (mt/user-http-request :crowberto :post 200 "action"+ {:name "Rename venues"+ :type "query"+ :database_id (mt/id)+ :collection_id collection-id+ :dataset_query (lib/native-query (mt/metadata-provider)+ "UPDATE venues SET name = {{name}}")+ :parameters [{:id "name" :slug "name" :type "string/="+ :target [:variable [:template-tag "name"]]}]}))))+ (testing "nobody else writes it"+ (mt/user-http-request :rasta :post 403 "card" {:name "Mine"+ :collection_id collection-id+ :display "table"+ :visualization_settings {}+ :dataset_query query}))))))))(deftest typed-schema-endpoint-test(mt/with-premium-features #{:data-apps}- (mt/with-actions-enabled- (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup :model/Card :model/Action]- (let [{collection-id :resource_collection_id} (mt/user-http-request :crowberto :post 200 "ee/apps" {:name "demo"})- mp (mt/metadata-provider)- query (-> (lib/query mp (lib.metadata/table mp (mt/id :venues)))- (lib/aggregate (lib/count))- (lib/breakout (lib.metadata/field mp (mt/id :venues :category_id))))- card (mt/user-http-request :crowberto :post 200 "card" {:name "Venues by category"- :collection_id collection-id- :display "table"- :visualization_settings {}- :dataset_query query})- action-id (:id (mt/user-http-request :crowberto :post 200 "action"- {:name "Rename venue"- :type "query"- :database_id (mt/id)- :collection_id collection-id- :dataset_query (lib/native-query mp "UPDATE venues SET name = {{name}} WHERE id = {{id}}")- :parameters [{:id "name" :slug "name" :type "string/="- :target [:variable [:template-tag "name"]]- :required true}- {:id "id" :slug "id" :type "number/="- :target [:variable [:template-tag "id"]]}]}))- action-entity-id (t2/select-one-fn :entity_id :model/Action :id action-id)]- (testing "a non-superuser cannot read it"- (mt/user-http-request :rasta :get 403 "ee/apps/demo/typed-schema"))- (let [{:keys [body headers]} (mt/user-http-request-full-response :crowberto :get 200 "ee/apps/demo/typed-schema")]- (is (str/starts-with? (get headers "Content-Type") "text/typescript"))- (testing "the module says how to fetch it again"- (is (str/includes? body "// mb data-app typed-schema demo --out src/metabase.ts\n")))- (testing "the module imports the define functions"- (is (str/includes? body "import { defineAction, defineQuery } from \"@metabase/embedding-sdk-react/data-app\";")))- (testing "a question is a card source addressed by its entity ID and typed by its result columns"- (is (str/includes? body "export const queries = {\n venuesByCategory: defineQuery({"))- (is (str/includes? body (str "entityId: \"" (:entity_id card) "\"")))- (is (str/includes? body "name: \"count\""))- (is (str/includes? body "jsType: \"number\"")))- (testing "an action is addressed by its entity ID and typed by its parameters"- (is (str/includes? body "export const actions = {\n renameVenue: defineAction({"))- (is (str/includes? body (str "id: \"" action-entity-id "\"")))- (is (str/includes? body "slug: \"name\",\n displayName: \"name\",\n jsType: \"string\",\n required: true,"))- (is (str/includes? body "slug: \"id\",\n displayName: \"id\",\n jsType: \"number\",")))))))))+ (data-apps.tu/with-published-tables! [(mt/id :venues)]+ (mt/with-actions-enabled+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup :model/Card :model/Action]+ (let [{collection-id :resource_collection_id} (mt/user-http-request :crowberto :post 200 "ee/apps" {:name "demo"})+ mp (mt/metadata-provider)+ query (-> (lib/query mp (lib.metadata/table mp (mt/id :venues)))+ (lib/aggregate (lib/count))+ (lib/breakout (lib.metadata/field mp (mt/id :venues :category_id))))+ card (mt/user-http-request :crowberto :post 200 "card" {:name "Venues by category"+ :collection_id collection-id+ :display "table"+ :visualization_settings {}+ :dataset_query query})+ action-id (:id (mt/user-http-request :crowberto :post 200 "action"+ {:name "Rename venue"+ :type "query"+ :database_id (mt/id)+ :collection_id collection-id+ :dataset_query (lib/native-query mp "UPDATE venues SET name = {{name}} WHERE id = {{id}}")+ :parameters [{:id "name" :slug "name" :type "string/="+ :target [:variable [:template-tag "name"]]+ :required true}+ {:id "id" :slug "id" :type "number/="+ :target [:variable [:template-tag "id"]]}]}))+ action-entity-id (t2/select-one-fn :entity_id :model/Action :id action-id)]+ (testing "a non-superuser cannot read it"+ (mt/user-http-request :rasta :get 403 "ee/apps/demo/typed-schema"))+ (let [{:keys [body headers]} (mt/user-http-request-full-response :crowberto :get 200 "ee/apps/demo/typed-schema")]+ (is (str/starts-with? (get headers "Content-Type") "text/typescript"))+ (testing "the module says how to fetch it again"+ (is (str/includes? body "// mb data-app typed-schema demo --out src/metabase.ts\n")))+ (testing "the module imports the define functions"+ (is (str/includes? body "import { defineAction, defineQuery } from \"@metabase/embedding-sdk-react/data-app\";")))+ (testing "a question is a card source addressed by its entity ID and typed by its result columns"+ (is (str/includes? body "export const queries = {\n venuesByCategory: defineQuery({"))+ (is (str/includes? body (str "entityId: \"" (:entity_id card) "\"")))+ (is (str/includes? body "name: \"count\""))+ (is (str/includes? body "jsType: \"number\"")))+ (testing "an action is addressed by its entity ID and typed by its parameters"+ (is (str/includes? body "export const actions = {\n renameVenue: defineAction({"))+ (is (str/includes? body (str "id: \"" action-entity-id "\"")))+ (is (str/includes? body "slug: \"name\",\n displayName: \"name\",\n jsType: \"string\",\n required: true,"))+ (is (str/includes? body "slug: \"id\",\n displayName: \"id\",\n jsType: \"number\","))))))))))(defn- create-question!"A table question named `card-name` in the collection with `collection-id`, reading `query`, created by an admin."@@ -545,18 +549,19 @@(deftest typed-schema-keys-are-the-same-on-every-instance-test(mt/with-premium-features #{:data-apps}- (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup :model/Card]- (let [{collection-id :resource_collection_id} (mt/user-http-request :crowberto :post 200 "ee/apps" {:name "demo"})- mp (mt/metadata-provider)- query (lib/query mp (lib.metadata/table mp (mt/id :venues)))- _ (create-question! collection-id "Café crème" query)- twins [(create-question! collection-id "Twin" query) (create-question! collection-id "Twin" query)]- symbols (create-question! collection-id "???" query)- body (mt/user-http-request :crowberto :get 200 "ee/apps/demo/typed-schema")- eid-part #(str/replace (:entity_id %) "-" "")]- (testing "a name keeps its letters, whatever their script"- (is (str/includes? body " caféCrème: defineQuery({")))- (testing "names that collide, or that have no letters, are told apart by entity ID"- (doseq [twin twins]- (is (str/includes? body (str " twin_" (eid-part twin) ": defineQuery({"))))- (is (str/includes? body (str " entity_" (eid-part symbols) ": defineQuery({"))))))))+ (data-apps.tu/with-published-tables! [(mt/id :venues)]+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup :model/Card]+ (let [{collection-id :resource_collection_id} (mt/user-http-request :crowberto :post 200 "ee/apps" {:name "demo"})+ mp (mt/metadata-provider)+ query (lib/query mp (lib.metadata/table mp (mt/id :venues)))+ _ (create-question! collection-id "Café crème" query)+ twins [(create-question! collection-id "Twin" query) (create-question! collection-id "Twin" query)]+ symbols (create-question! collection-id "???" query)+ body (mt/user-http-request :crowberto :get 200 "ee/apps/demo/typed-schema")+ eid-part #(str/replace (:entity_id %) "-" "")]+ (testing "a name keeps its letters, whatever their script"+ (is (str/includes? body " caféCrème: defineQuery({")))+ (testing "names that collide, or that have no letters, are told apart by entity ID"+ (doseq [twin twins]+ (is (str/includes? body (str " twin_" (eid-part twin) ": defineQuery({"))))+ (is (str/includes? body (str " entity_" (eid-part symbols) ": defineQuery({")))))))))diff --git a/enterprise/backend/test/metabase_enterprise/data_apps/group_access_warnings_test.clj b/enterprise/backend/test/metabase_enterprise/data_apps/group_access_warnings_test.cljindex 0d8fa728916..1a4dd5d4eaf 100644--- a/enterprise/backend/test/metabase_enterprise/data_apps/group_access_warnings_test.clj+++ b/enterprise/backend/test/metabase_enterprise/data_apps/group_access_warnings_test.clj@@ -2,6 +2,7 @@(:require[clojure.test :refer :all][metabase-enterprise.data-apps.group-access :as group-access]+ [metabase-enterprise.data-apps.test-util :as data-apps.tu][metabase-enterprise.dependencies.test-util :as deps.test][metabase.lib.core :as lib][metabase.lib.metadata :as lib.metadata]@@ -13,70 +14,93 @@(set! *warn-on-reflection* true)(defn- do-with-app-reading!- "Call `f` with a data app whose resource collection holds a card that reads `table-ids`."+ "Call `f` with a data app whose resource collection holds a venues question that the dependency graph says reads+ `table-ids`."[table-ids f]- (mt/with-temp [:model/DataApp app {:name "birds" :display_name "Birds" :bundle_path "birds.js"}- :model/Card card {:collection_id (:resource_collection_id app)}]- (mt/with-model-cleanup [:model/Dependency]- (when (seq table-ids)- (t2/insert! :model/Dependency- (for [table-id table-ids]- {:from_entity_type :card :from_entity_id (:id card)- :to_entity_type :table :to_entity_id table-id})))- (f app))))+ (data-apps.tu/with-published-tables! [(mt/id :venues)]+ (mt/with-temp [:model/DataApp app {:name "birds" :display_name "Birds" :bundle_path "birds.js"}+ :model/Card card {:collection_id (:resource_collection_id app) :dataset_query (data-apps.tu/venues-query)}]+ (mt/with-model-cleanup [:model/Dependency]+ (when (seq table-ids)+ (t2/insert! :model/Dependency+ (for [table-id table-ids]+ {:from_entity_type :card :from_entity_id (:id card)+ :to_entity_type :table :to_entity_id table-id})))+ (f app)))))(defmacro ^{:private true :clj-kondo/lint-as 'clojure.core/let} with-app-reading!"Bind `app-sym` to a data app whose resource collection reads `table-ids`, and run `body`."[[app-sym table-ids] & body]`(do-with-app-reading! ~table-ids (fn [~app-sym] ~@body)))+(defn- do-with-query-action!+ "Call `f` with a query action running `sql` in the collection with `collection-id`."+ [collection-id sql f]+ (mt/with-temp [:model/Action {action-id :id} {:type :query :name "Run" :collection_id collection-id}+ :model/QueryAction _ {:action_id action-id+ :database_id (mt/id)+ :dataset_query (lib/native-query (mt/metadata-provider) sql)}]+ (f)))+(deftest group-permission-warnings-walk-the-dependency-graph-test- (testing "the warnings list the tables a native card, a card on another card, and a query action read"+ (testing "the warnings list the tables a question reads, the tables only a Library metric it aggregates reads, and the+ tables a query action writes"(mt/with-premium-features #{:data-apps :advanced-permissions :dependencies}(mt/with-no-data-perms-for-all-users!(mt/with-model-cleanup [:model/Dependency :model/DependencyStatus]- (let [mp (mt/metadata-provider)]- (mt/with-temp [:model/DataApp {collection-id :resource_collection_id :as app}- {:name "birds" :display_name "Birds" :bundle_path "birds.js"}- :model/Card {base-id :id} {:collection_id collection-id- :dataset_query (lib/query mp (lib.metadata/table mp (mt/id :orders)))}- :model/Card _ {:collection_id collection-id- :dataset_query (lib/native-query mp "SELECT * FROM VENUES")}- :model/PermissionsGroup group {}]- (mt/with-temp [:model/Card _ {:collection_id collection-id- :dataset_query (lib/query mp (lib.metadata/card mp base-id))}- :model/Action {action-id :id} {:type :query :name "Delete" :collection_id collection-id}- :model/QueryAction _ {:action_id action-id- :database_id (mt/id)- :dataset_query (lib/native-query mp "DELETE FROM CHECKINS WHERE ID = 1")}]- (deps.test/synchronously-run-dependency-job!)- (perms/set-database-permission! (:id group) (mt/id) :perms/view-data :blocked)- (group-access/add-groups! app [(:id group)])- (is (=? [{:group_id (:id group)- :missing_tables [{:id (mt/id :checkins)} {:id (mt/id :orders)} {:id (mt/id :venues)}]}]- (group-access/permission-warnings app)))))))))))+ (data-apps.tu/with-published-tables! [(mt/id :orders) (mt/id :venues)]+ (data-apps.tu/do-with-library!+ (fn [{:keys [metrics-id]}]+ (let [mp (mt/metadata-provider)]+ (mt/with-temp [:model/Card {metric-id :id} {:name "Venue categories"+ :type :metric+ :collection_id metrics-id+ :dataset_query (let [venues (lib/query mp (lib.metadata/table mp (mt/id :venues)))]+ ;; CATEGORIES is reached only through this metric+ (lib/aggregate venues (lib/distinct (some #(when (= (mt/id :categories :name) (:id %)) %)+ (lib/visible-columns venues)))))}+ :model/DataApp {collection-id :resource_collection_id :as app}+ {:name "birds" :display_name "Birds" :bundle_path "birds.js"}+ :model/Card _ {:collection_id collection-id+ :dataset_query (lib/query mp (lib.metadata/table mp (mt/id :orders)))}+ :model/PermissionsGroup group {}]+ (let [mp (mt/metadata-provider)]+ (mt/with-temp [:model/Card _ {:collection_id collection-id+ :dataset_query (-> (lib/query mp (lib.metadata/table mp (mt/id :venues)))+ (lib/aggregate (lib.metadata/metric mp metric-id)))}]+ (do-with-query-action!+ collection-id "DELETE FROM CHECKINS WHERE ID = 1"+ (fn []+ (deps.test/synchronously-run-dependency-job!)+ (perms/set-database-permission! (:id group) (mt/id) :perms/view-data :blocked)+ (group-access/add-groups! app [(:id group)])+ (is (=? [{:group_id (:id group)+ :missing_tables [{:id (mt/id :categories)} {:id (mt/id :checkins)}+ {:id (mt/id :orders)} {:id (mt/id :venues)}]}]+ (group-access/permission-warnings app)))))))))))))))))(deftest group-permission-warnings-include-tables-in-optional-clauses-test- (testing "the tables an optional clause names count, whether or not its parameter is set"+ (testing "the tables an optional clause of a query action names count, whether or not its parameter is set"(mt/with-premium-features #{:data-apps :advanced-permissions :dependencies}(mt/with-no-data-perms-for-all-users!(mt/with-model-cleanup [:model/Dependency :model/DependencyStatus]- (doseq [sql ["SELECT * FROM VENUES [[WHERE ID IN (SELECT VENUE_ID FROM CHECKINS WHERE ID = {{id}})]]"- "SELECT * FROM VENUES v [[JOIN CHECKINS c ON c.VENUE_ID = v.ID AND c.ID = {{id}}]]"]]+ (doseq [sql ["UPDATE VENUES SET NAME = 'x' [[WHERE ID IN (SELECT VENUE_ID FROM CHECKINS WHERE ID = {{id}})]]"+ "UPDATE VENUES v SET NAME = 'x' WHERE v.ID IN (SELECT v2.ID FROM VENUES v2 [[JOIN CHECKINS c ON c.VENUE_ID = v2.ID AND c.ID = {{id}}]])"]](testing sql(mt/with-temp [:model/DataApp {collection-id :resource_collection_id :as app}{:name "birds" :display_name "Birds" :bundle_path "birds.js"}- :model/Card _ {:collection_id collection-id- :dataset_query (lib/native-query (mt/metadata-provider) sql)}:model/PermissionsGroup group {}]- (perms/set-database-permission! (:id group) (mt/id) :perms/view-data :blocked)- (group-access/add-groups! app [(:id group)])- (deps.test/synchronously-run-dependency-job!)- (is (=? [{:group_id (:id group) :missing_tables [{:id (mt/id :checkins)} {:id (mt/id :venues)}]}]- (group-access/permission-warnings app)))))))))))+ (do-with-query-action!+ collection-id sql+ (fn []+ (perms/set-database-permission! (:id group) (mt/id) :perms/view-data :blocked)+ (group-access/add-groups! app [(:id group)])+ (deps.test/synchronously-run-dependency-job!)+ (is (=? [{:group_id (:id group) :missing_tables [{:id (mt/id :checkins)} {:id (mt/id :venues)}]}]+ (group-access/permission-warnings app)))))))))))))(deftest group-permission-warnings-follow-snippet-edit-test- (testing "after a snippet edit and the jobs, the warnings list the tables of the snippet's new SQL"+ (testing "after a snippet edit and the jobs, the warnings list the tables of the snippet's new SQL in a query action"(mt/test-helpers-set-global-values!(mt/with-premium-features #{:data-apps :advanced-permissions :dependencies}(mt/with-no-data-perms-for-all-users!@@ -84,17 +108,17 @@(mt/with-temp [:model/NativeQuerySnippet snippet {:name "birds source" :content "VENUES"}:model/DataApp {collection-id :resource_collection_id :as app}{:name "birds" :display_name "Birds" :bundle_path "birds.js"}- :model/Card _ {:collection_id collection-id- :dataset_query (lib/native-query (mt/metadata-provider)- "SELECT * FROM {{snippet: birds source}}")}:model/PermissionsGroup group {}]- (perms/set-database-permission! (:id group) (mt/id) :perms/view-data :blocked)- (group-access/add-groups! app [(:id group)])- (deps.test/synchronously-run-dependency-job!)- (t2/update! :model/NativeQuerySnippet (:id snippet) {:content "CHECKINS"})- (deps.test/synchronously-run-dependency-job!)- (is (=? [{:group_id (:id group) :missing_tables [{:id (mt/id :checkins)}]}]- (group-access/permission-warnings app))))))))))+ (do-with-query-action!+ collection-id "DELETE FROM {{snippet: birds source}} WHERE ID = 1"+ (fn []+ (perms/set-database-permission! (:id group) (mt/id) :perms/view-data :blocked)+ (group-access/add-groups! app [(:id group)])+ (deps.test/synchronously-run-dependency-job!)+ (t2/update! :model/NativeQuerySnippet (:id snippet) {:content "CHECKINS"})+ (deps.test/synchronously-run-dependency-job!)+ (is (=? [{:group_id (:id group) :missing_tables [{:id (mt/id :checkins)}]}]+ (group-access/permission-warnings app))))))))))))(deftest group-permission-warnings-exclude-inactive-tables-test(mt/with-premium-features #{:data-apps :advanced-permissions}diff --git a/enterprise/backend/test/metabase_enterprise/data_apps/invariants_test.clj b/enterprise/backend/test/metabase_enterprise/data_apps/invariants_test.cljnew file mode 100644index 00000000000..314d9af5064--- /dev/null+++ b/enterprise/backend/test/metabase_enterprise/data_apps/invariants_test.clj@@ -0,0 +1,313 @@+(ns metabase-enterprise.data-apps.invariants-test+ "What a data app's collection may hold, enforced by the model hooks, so a write through Toucan, which is what a+ remote-sync pull does, is refused like an API call."+ (:require+ [clojure.string :as str]+ [clojure.test :refer :all]+ [metabase-enterprise.data-apps.test-util :as data-apps.tu]+ [metabase.lib.core :as lib]+ [metabase.lib.metadata :as lib.metadata]+ [metabase.test :as mt]+ [toucan2.core :as t2]))++(set! *warn-on-reflection* true)++(defn- do-with-app-collection+ "Call `f` with the id of a data app's resource collection; deleting the app afterwards deletes what it holds."+ [f]+ (mt/with-premium-features #{:data-apps}+ (mt/with-temp [:model/DataApp {collection-id :resource_collection_id}+ {:name "birds" :display_name "Birds" :bundle_path "birds.js"}]+ (f collection-id))))++(defn- reading-card+ "A native query of the action kind that reads the card with `card-id` through a card template tag."+ [card-id]+ (let [tag (str "#" card-id)]+ (lib/query (mt/metadata-provider)+ {:database (mt/id)+ :type :native+ :native {:query (str "SELECT * FROM {{" tag "}}")+ :template-tags {tag {:type :card+ :card-id card-id+ :name tag+ :display-name tag+ :id (str (random-uuid))}}}})))++(defn- insert-query-action!+ "Insert a query action named `action-name` running `query` in the collection with `collection-id`, as a load does,+ with `action-columns` merged into its Action row."+ [collection-id action-name query & [action-columns]]+ (let [action-id (t2/insert-returning-pk! :model/Action (merge {:name action-name+ :type :query+ :collection_id collection-id+ :creator_id (mt/user->id :crowberto)}+ action-columns))]+ (t2/insert! :model/QueryAction {:action_id action-id :database_id (mt/id) :dataset_query query})+ action-id))++(deftest card-in-apps-collection-holds-query-test+ (testing "a card in an app's collection holds a query on a database"+ (do-with-app-collection+ (fn [collection-id]+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"must hold a query on a database"+ (t2/insert! :model/Card {:name "Empty"+ :display "table"+ :visualization_settings {}+ :creator_id (mt/user->id :crowberto)+ :collection_id collection-id+ :dataset_query {}})))))))++(deftest action-in-apps-collection-is-neither-archived-nor-public-test+ (testing "an action is refused archived or public on insert, not only on update"+ (do-with-app-collection+ (fn [collection-id]+ (let [query (lib/native-query (mt/metadata-provider) "UPDATE venues SET name = 'x'")]+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"can't be archived"+ (insert-query-action! collection-id "Archived" query {:archived true})))+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"can't be made public"+ (insert-query-action! collection-id "Public" query+ {:public_uuid (str (random-uuid))+ :made_public_by_id (mt/user->id :crowberto)})))+ (testing "elsewhere both are fine"+ (mt/with-temp [:model/Collection {other-id :id} {:namespace :data-actions}]+ (is (pos-int? (insert-query-action! other-id "Archived elsewhere" query {:archived true})))+ (is (pos-int? (insert-query-action! other-id "Public elsewhere" query+ {:public_uuid (str (random-uuid))+ :made_public_by_id (mt/user->id :crowberto)}))))))))))++(deftest action-in-apps-collection-takes-no-values-from-card-test+ (testing "a parameter of an action in an app's collection takes no values from a card"+ (do-with-app-collection+ (fn [collection-id]+ (mt/with-temp [:model/Card {card-id :id} {:name "Elsewhere"}]+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"can't take a parameter's values from a card"+ (insert-query-action!+ collection-id "Rename" (lib/native-query (mt/metadata-provider) "UPDATE venues SET name = {{name}}")+ {:parameters [{:id "name"+ :slug "name"+ :type :string/=+ :values_source_type "card"+ :values_source_config {:card_id card-id}}]}))))))))++(deftest action-in-apps-collection-reads-only-apps-cards-test+ (testing "a query action in an app's collection reads no card outside it, when it is written as a load writes it"+ (do-with-app-collection+ (fn [collection-id]+ (data-apps.tu/with-published-tables! [(mt/id :venues)]+ (mt/with-temp [:model/Card {outside-id :id} {:name "Elsewhere"}+ :model/Card {own-id :id} {:name "Own"+ :collection_id collection-id+ :dataset_query (data-apps.tu/venues-query)}]+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"can read only the app's own cards"+ (insert-query-action! collection-id "Reads outside" (reading-card outside-id))))+ (let [action-id (insert-query-action! collection-id "Reads own" (reading-card own-id))]+ (testing "changing its query to read a card outside is refused"+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"can read only the app's own cards"+ (t2/update! :model/QueryAction action-id {:dataset_query (reading-card outside-id)})))))+ (testing "moving an action that reads a card outside into the collection is refused"+ (mt/with-temp [:model/Collection {other-id :id} {:namespace :data-actions}]+ (let [action-id (insert-query-action! other-id "Moved in" (reading-card outside-id))]+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"can read only the app's own cards"+ (t2/update! :model/Action action-id {:collection_id collection-id})))+ (is (= other-id (t2/select-one-fn :collection_id :model/Action :id action-id))))))))))))++(deftest action-in-apps-collection-has-no-implicit-row-test+ (testing "an action in an app's collection is a query action, so it gets no implicit action row"+ (do-with-app-collection+ (fn [collection-id]+ (let [action-id (insert-query-action! collection-id "Query" (lib/native-query (mt/metadata-provider) "SELECT 1"))]+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"can't have an implicit action"+ (t2/insert! :model/ImplicitAction {:action_id action-id :kind "row/create"}))))))))++(deftest two-data-apps-cannot-share-collection-test+ (testing "the database refuses a second app on a collection another app already owns"+ (mt/with-model-cleanup [:model/DataApp]+ (do-with-app-collection+ (fn [collection-id]+ (let [insert! (fn [slug collection-id]+ (t2/query-one {:insert-into :data_app+ :values [{:name slug+ :display_name slug+ :bundle_path "index.js"+ :entity_id (data-apps.tu/app-entity-id slug)+ :resource_collection_id collection-id+ :created_at :%now+ :updated_at :%now}]}))]+ (mt/with-temp [:model/Collection {free-id :id} {:namespace :data-apps}]+ (testing "the same row on a collection no app owns goes in"+ (insert! "sparrows" free-id)+ (is (t2/exists? :model/DataApp :name "sparrows")))+ (is (thrown? Exception (t2/with-transaction [_conn]+ (insert! "finches" collection-id))))+ (is (not (t2/exists? :model/DataApp :name "finches"))))))))))++(deftest data-apps-collection-is-root-collection-of-its-namespace-test+ (testing "an app given an existing collection gets it only when it is a plain top-level collection of data apps that+ no other app has"+ (mt/with-premium-features #{:data-apps}+ (mt/with-model-cleanup [:model/DataApp]+ (mt/with-temp [:model/Collection {default-id :id} {:name "Finance"}+ :model/Collection {root-id :id} {:name "Root" :namespace :data-apps}+ :model/Collection {archived-id :id} {:name "Archived" :namespace :data-apps :archived true}+ :model/Collection {official-id :id} {:name "Official" :namespace :data-apps :authority_level "official"}+ :model/Collection {synced-id :id} {:name "Synced" :namespace :data-apps :is_remote_synced true}]+ (let [app! (fn [slug collection-id]+ (t2/insert-returning-pk! :model/DataApp {:name slug+ :display_name slug+ :bundle_path "index.js"+ :resource_collection_id collection-id}))]+ (doseq [[label collection-id] [["a default-namespace collection" default-id]+ ["an archived collection" archived-id]+ ["an official collection" official-id]]]+ (testing label+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"must be a top-level collection of data apps"+ (app! "refused" collection-id)))))+ (testing "a remote-synced one is fine, as remote sync marks an app's collection"+ (is (pos-int? (app! "synced" synced-id))))+ (testing "a top-level collection of data apps is fine"+ (let [app-id (app! "accepted" root-id)]+ (testing "but not for a second app"+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"already belongs to another data app"+ (app! "second" root-id))))+ (testing "an app whose collection is gone is given one the same way"+ (t2/query-one {:update :data_app :set {:resource_collection_id nil} :where [:= :id app-id]})+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"must be a top-level collection of data apps"+ (t2/update! :model/DataApp app-id {:resource_collection_id default-id})))+ (t2/update! :model/DataApp app-id {:resource_collection_id root-id})+ (is (= root-id (t2/select-one-fn :resource_collection_id :model/DataApp :id app-id))))))))))))++(deftest content-of-data-apps-namespace-is-checked-before-its-app-loads-test+ (testing "a load may write a collection's content before the app that owns it, so the namespace decides"+ (mt/with-premium-features #{:data-apps}+ (mt/with-temp [:model/Collection {collection-id :id} {:name "Not yet an app's" :namespace :data-apps}]+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"must be built with the query builder"+ (mt/with-temp [:model/Card _ {:collection_id collection-id+ :dataset_query (lib/native-query (mt/metadata-provider) "SELECT 1")}])))+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"can't be archived"+ (insert-query-action! collection-id "Archived" (lib/native-query (mt/metadata-provider) "SELECT 1")+ {:archived true})))))))++(deftest apps-collection-stays-what-it-was-given-as-test+ (testing "an app's collection can't later be moved, typed or made a sample, but remote sync may sync it and a restore may clear its+ archive marker"+ (do-with-app-collection+ (fn [collection-id]+ (mt/with-temp [:model/Collection {other-id :id} {:name "Other" :namespace :data-apps}]+ (doseq [changes [{:type "library-metrics"} {:is_sample true}+ {:location (str "/" other-id "/")}]]+ (testing (pr-str changes)+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"stays a top-level collection of data apps"+ (t2/update! :model/Collection collection-id changes)))))+ (t2/update! :model/Collection collection-id {:archive_operation_id nil :is_remote_synced true :description "Birds"})+ (is (true? (t2/select-one-fn :is_remote_synced :model/Collection :id collection-id)))+ (is (= "Birds" (t2/select-one-fn :description :model/Collection :id collection-id))))))))++(deftest moving-action-into-apps-collection-is-checked-test+ (testing "an action moved into an app's collection, as a pull may move one, meets the same rules as one created there"+ (do-with-app-collection+ (fn [collection-id]+ (mt/with-temp [:model/Collection {other-id :id} {:namespace :data-actions}+ :model/Card {card-id :id} {:name "Elsewhere"}]+ (let [query (lib/native-query (mt/metadata-provider) "UPDATE venues SET name = {{name}}")]+ (doseq [[label columns message] [["archived" {:archived true} #"can't be archived"]+ ["public" {:public_uuid (str (random-uuid)) :made_public_by_id (mt/user->id :crowberto)}+ #"can't be made public"]+ ["taking parameter values from a card"+ {:parameters [{:id "name" :slug "name" :type :string/=+ :values_source_type "card"+ :values_source_config {:card_id card-id}}]}+ #"can't take a parameter's values from a card"]]]+ (testing label+ (let [action-id (insert-query-action! other-id (str "Moved " label) query columns)]+ (is (thrown-with-msg? clojure.lang.ExceptionInfo message+ (t2/update! :model/Action action-id {:collection_id collection-id})))+ (is (= other-id (t2/select-one-fn :collection_id :model/Action :id action-id))))))))+ (testing "an action of a model"+ (mt/with-actions-enabled+ (mt/with-temp [:model/Collection {model-coll :id} {:name "Models"}+ :model/Card {model-id :id} {:type :model :collection_id model-coll+ :dataset_query (data-apps.tu/venues-query)}]+ (let [action-id (t2/insert-returning-pk! :model/Action {:name "Of a model" :type :query :model_id model-id+ :creator_id (mt/user->id :crowberto)})]+ (t2/insert! :model/QueryAction {:action_id action-id :database_id (mt/id)+ :dataset_query (lib/native-query (mt/metadata-provider) "SELECT 1")})+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"query action of no model"+ (t2/update! :model/Action action-id {:collection_id collection-id})))+ (is (= model-coll (t2/select-one-fn :collection_id :model/Action :id action-id)))))))))))++(deftest card-in-apps-collection-reads-only-published-tables-through-its-macros-test+ (testing "segments, measures and remapped columns count as reads of the tables they reach"+ (do-with-app-collection+ (fn [collection-id]+ (data-apps.tu/with-published-tables! [(mt/id :venues)]+ (let [mp (mt/metadata-provider)+ venues (lib/query mp (lib.metadata/table mp (mt/id :venues)))+ category (some #(when (= (mt/id :categories :name) (:id %)) %) (lib/filterable-columns venues))+ save! (fn [query]+ (mt/with-temp [:model/Card _ {:name "Saved" :collection_id collection-id :dataset_query query}]))]+ (mt/with-temp [:model/Segment {segment-id :id} {:name "Bars"+ :table_id (mt/id :venues)+ :definition (lib/filter venues (lib/= category "Bar"))}+ :model/Measure {measure-id :id} {:name "Categories"+ :table_id (mt/id :venues)+ :definition (lib/aggregate venues (lib/distinct category))}]+ (let [mp (mt/metadata-provider)]+ (testing "a segment that filters on an unpublished table"+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"not CATEGORIES"+ (save! (lib/filter venues (lib.metadata/segment mp segment-id))))))+ (testing "a measure that aggregates one"+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"not CATEGORIES"+ (save! (lib/aggregate venues (lib.metadata/measure mp measure-id))))))))+ (testing "a column remapped to an unpublished table's column"+ (mt/with-temp [:model/Dimension _ {:field_id (mt/id :venues :category_id)+ :name "Category"+ :type :external+ :human_readable_field_id (mt/id :categories :name)}]+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"not CATEGORIES"+ (save! (lib/query (mt/metadata-provider)+ (lib.metadata/table (mt/metadata-provider) (mt/id :venues))))))))))))))++(deftest card-in-apps-collection-stays-editable-after-its-table-is-unpublished-test+ (testing "a later change that leaves the query alone keeps working; one that changes it is checked again"+ (do-with-app-collection+ (fn [collection-id]+ (let [card-id (data-apps.tu/with-published-tables! [(mt/id :venues)]+ (t2/insert-returning-pk! :model/Card {:name "Venues"+ :display "table"+ :visualization_settings {}+ :creator_id (mt/user->id :crowberto)+ :collection_id collection-id+ :dataset_query (data-apps.tu/venues-query)}))]+ (t2/update! :model/Card card-id {:name "Renamed" :description "Still venues"})+ (is (= "Renamed" (t2/select-one-fn :name :model/Card :id card-id)))+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"not VENUES"+ (t2/update! :model/Card card-id {:dataset_query (lib/limit (data-apps.tu/venues-query) 10)}))))))))++(deftest card-in-apps-collection-is-in-no-document-test+ (testing "a card that belongs to a document elsewhere can't be in an app's collection"+ (do-with-app-collection+ (fn [collection-id]+ (data-apps.tu/with-published-tables! [(mt/id :venues)]+ (mt/with-temp [:model/Document {document-id :id} {:name "Notes"}]+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"in no dashboard or document"+ (t2/insert! :model/Card {:name "In a document"+ :display "table"+ :visualization_settings {}+ :creator_id (mt/user->id :crowberto)+ :collection_id collection-id+ :document_id document-id+ :dataset_query (data-apps.tu/venues-query)})))))))))++(deftest refusals-name-cards-test+ (testing "a refusal names a card by its name, not only by its id on this instance"+ (do-with-app-collection+ (fn [collection-id]+ (data-apps.tu/with-published-tables! [(mt/id :venues)]+ (mt/with-temp [:model/Card {card-id :id} {:name "Venues elsewhere" :dataset_query (data-apps.tu/venues-query)}]+ (let [message (try (mt/with-temp [:model/Card _ {:collection_id collection-id+ :dataset_query (lib/query (mt/metadata-provider)+ (lib.metadata/card (mt/metadata-provider) card-id))}])+ nil+ (catch clojure.lang.ExceptionInfo e (ex-message e)))]+ (is (str/includes? message (format "\"Venues elsewhere\" (%d)" card-id))))))))))diff --git a/enterprise/backend/test/metabase_enterprise/data_apps/resource_validation_test.clj b/enterprise/backend/test/metabase_enterprise/data_apps/resource_validation_test.cljdeleted file mode 100644index 4d39f5d9b49..00000000000--- a/enterprise/backend/test/metabase_enterprise/data_apps/resource_validation_test.clj+++ /dev/null@@ -1,453 +0,0 @@-(ns metabase-enterprise.data-apps.resource-validation-test- "What the files of a data app's collection may hold, checked on the ingested files before anything loads."- (:require- [clojure.string :as str]- [clojure.test :refer :all]- [metabase-enterprise.data-apps.core :as data-apps]- [metabase-enterprise.data-apps.test-util :as data-apps.tu]- [metabase-enterprise.serialization.core :as serialization]- [metabase.test :as mt]- [metabase.util.yaml :as yaml]- [toucan2.core :as t2]))--(set! *warn-on-reflection* true)--(def ^:private collection-eid (data-apps.tu/collection-entity-id "shop"))--(def ^:private question-eid "shopQuestionListVenue")--(defn- venues-query []- {:stages [{:source {:type "table" :id (mt/id :venues)} :limit 5}]})--(defn- ingest [content]- (serialization/read-timestamps (yaml/parse-string content {:key-fn serialization/parse-key})))--(defn- files- "The data app entity files of the repo `tree`, as ingestion hands them to the check."- [tree]- (for [[path content] tree- :when (str/ends-with? path ".yaml")]- {:path path :entity (ingest content)}))--(def ^:private collection-name "Data App: shop")--(def ^:private collection-dir (str "collections/data_apps/" (data-apps.tu/collection-dir collection-name) "/"))--(def ^:private collection-path (data-apps.tu/collection-path collection-name))--(def ^:private question-path (str collection-dir "venueslist_"))--(def ^:private action-path (str collection-dir "rename_venue_"))--(defn- shop- "The repo files of the `shop` app with `resources`, a map of repo paths to YAML text (see `data-apps.tu/app-files`)."- [resources & {:as options}]- (data-apps.tu/app-files "shop" (merge {:name "Shop" :path "index.js" :bundle "B"- :collection collection-eid :resources resources}- options)))--(defn- question-resources []- (data-apps.tu/build-resources collection-name collection-eid [{:entity_id question-eid :name "VenuesList" :query (venues-query)}] []))--(defn- edit-file- "`tree` with the YAML of the first file whose path starts with `prefix` changed by `f`."- [tree prefix f]- (let [path (some #(when (str/starts-with? % prefix) %) (sort (keys tree)))]- (update tree path #(yaml/generate-string (f (yaml/parse-string %))))))--(defn- messages [tree]- (mapv :message (data-apps/problems (files tree))))--(defn- warnings [tree]- (mapv :message (data-apps/warnings (files tree))))--(defn- first-problem [tree]- (first (data-apps/problems (files tree))))--(deftest valid-resources-have-no-problems-test- (data-apps.tu/do-with-sources!- (fn [{:keys [metric-id action-id]}]- (let [resources (data-apps.tu/build-resources- collection-name collection-eid- [{:entity_id question-eid :name "VenuesList" :query (venues-query)}- {:entity_id "shopQuestionMetricVen" :name "VenueCount"- :query {:stages [{:source {:type "table" :id (mt/id :venues)}- :aggregations [{:type "metric" :id metric-id}]}]}}]- [action-id])]- (is (= [] (messages (shop resources))))))))--(deftest an-app-with-only-its-collection-has-no-problems-test- (is (= [] (messages (data-apps.tu/app-files "shop" {:name "Shop" :path "index.js" :bundle "B" :collection collection-eid})))))--(deftest a-file-is-named-with-its-problem-test- (let [tree (edit-file (shop (question-resources)) question-path #(assoc % :archived true))]- (is (=? {:file #"collections/data_apps/data_app__shop/.*\.yaml" :message #".*must not be archived\."}- (first-problem tree)))))--(deftest refuses-what-a-resource-may-not-hold-test- (let [refused (fn [tree message]- (is (some #(str/includes? % message) (messages tree)) message))]- (testing "a manifest naming a collection whose file isn't in the repository"- (refused (shop (question-resources) :collection (data-apps.tu/collection-entity-id "other"))- "is not in the repository"))- (testing "a card that isn't a question or metric: a model has no place, now that no action hangs off one"- (doseq [card-type ["dashboard" "model"]]- (refused (edit-file (shop (question-resources)) question-path #(assoc % :type card-type))- "must be a question or metric")))- (testing "a card whose query names no database"- (refused (edit-file (shop (question-resources)) question-path #(assoc % :dataset_query {}))- "must hold a query"))- (testing "a public card"- (refused (edit-file (shop (question-resources)) question-path #(assoc % :public_uuid "8e2a9c55-6b0f-4b43-a1c4-fb5c0c1b2b0a"))- "must not be public or embedded"))- (testing "a card that reads a card outside the app"- (mt/with-temp [:model/Card {other-id :id} {:dataset_query {:database (mt/id)- :type :query- :query {:source-table (mt/id :venues)}}}]- (let [other-eid (t2/select-one-fn :entity_id :model/Card :id other-id)]- (refused (edit-file (shop (question-resources)) question-path- #(update % :dataset_query assoc :stages [{:lib/type "mbql.stage/mbql" :source-card other-eid}]))- (str "references Card " other-eid)))))- (testing "a file whose serdes/meta doesn't identify what it holds"- (refused (edit-file (shop (question-resources)) question-path #(assoc % :serdes/meta [{:model "Card" :id "someOtherEntityId0001"}]))- "must hold a single Card whose serdes/meta ID is its entity_id"))- (testing "a manifest that doesn't identify the app, which a load would refuse"- (refused (edit-file (shop nil) "data_apps/shop/data_app.yaml" #(dissoc % :entity_id))- "must hold a single DataApp whose serdes/meta ID is its entity_id")- (refused (edit-file (shop nil) "data_apps/shop/data_app.yaml" #(assoc % :entity_id "someOtherEntityId0001"))- "must hold a single DataApp whose serdes/meta ID is its entity_id"))- (testing "a manifest naming no collection"- (refused (shop (question-resources) :collection nil) "must name the app's resource collection")- (refused (shop nil :collection nil) "must name the app's resource collection"))- (testing "a manifest naming a collection the repository doesn't hold"- (refused (shop (dissoc (question-resources) collection-path)) "is not in the repository")- (refused (shop nil) "is not in the repository"))))--(deftest refuses-an-action-the-app-cannot-run-test- (data-apps.tu/do-with-sources!- (fn [{:keys [model-id action-id]}]- (let [model-eid (t2/select-one-fn :entity_id :model/Card :id model-id)- resources (data-apps.tu/build-resources collection-name collection-eid- [{:entity_id question-eid :name "VenuesList" :query (venues-query)}]- [action-id])]- (is (= [] (messages (shop resources))) "a query action that belongs to no model is fine")- (testing "a data app runs only actions that belong to no model, the ones the typed schema lists"- (is (some #(str/includes? % "must belong to no model")- (messages (edit-file (shop resources) action-path #(assoc % :model_id model-eid))))))- (testing "and only query actions"- (is (some #(str/includes? % "must be a query action")- (messages (edit-file (shop resources) action-path- #(assoc % :type "implicit" :query [] :implicit [{:kind "row/create"}])))))- (is (some #(str/includes? % "must carry exactly one query, and no implicit action")- (messages (edit-file (shop resources) action-path #(assoc % :implicit [{:kind "row/create"}]))))))- (testing "a card or action has to name its creator, since a load can't save one without"- (is (some #(str/includes? % "must name its creator in creator_id")- (messages (edit-file (shop resources) action-path #(dissoc % :creator_id)))))- (is (some #(str/includes? % "must name its creator in creator_id")- (messages (edit-file (shop resources) question-path #(dissoc % :creator_id))))))- (testing "an action outside the app's collection isn't the app's, so it isn't checked as its resource"- (is (= [] (messages (edit-file (shop resources) action-path #(assoc % :collection_id "elsewhere0000000000a" :model_id model-eid))))))))))--(defn- names-its-file?- "Whether each problem of `tree` names its file in its message, which a pull lists alone."- [tree]- (every? (fn [{:keys [file message]}] (str/includes? message file))- (data-apps/problems (files tree))))--(deftest refuses-what-this-app-does-not-own-test- (testing "serialization would update any row carrying an entity ID a file names, so a file may only name the app's own"- (testing "a card whose entity ID belongs to a card elsewhere"- (mt/with-temp [:model/Card _ {:name "Someone else's" :entity_id question-eid}]- (is (some #(str/includes? % (str "Card " question-eid ", which already exists outside")) (messages (shop (question-resources)))))- (is (names-its-file? (shop (question-resources))))))- (testing "a collection that is another app's"- (mt/with-temp [:model/Collection {collection-id :id} {:entity_id collection-eid :name "Theirs" :namespace :data-apps}- :model/DataApp _ {:name "theirs" :display_name "Theirs" :bundle_path "index.js"- :resource_collection_id collection-id}]- (is (some #(str/includes? % "already exists and is another data app's collection") (messages (shop (question-resources)))))- (is (names-its-file? (shop (question-resources))))))- (testing "a collection outside the data-apps namespace, which a load would move into it"- (mt/with-temp [:model/Collection _ {:entity_id collection-eid :name "Finance"}]- (is (some #(str/includes? % "already exists outside the data-apps namespace") (messages (shop (question-resources)))))- (is (names-its-file? (shop (question-resources))))))- (testing "the app's own collection and card"- (mt/with-temp [:model/Collection {collection-id :id} {:entity_id collection-eid :name "Mine" :namespace :data-apps}- :model/DataApp _ {:name "shop" :display_name "Shop" :bundle_path "index.js"- :entity_id (data-apps.tu/app-entity-id "shop")- :resource_collection_id collection-id}- :model/Card _ {:name "Mine" :entity_id question-eid :collection_id collection-id}]- (is (= [] (messages (shop (question-resources)))))))))--(deftest warns-of-a-field-that-doesnt-exist-test- (testing "a field a query names that doesn't exist loads as a placeholder and is logged, on a database without schemas too"- (mt/with-temp [:model/Database {db-id :id} {:engine :h2 :name "no-schemas"}- :model/Table {table-id :id} {:db_id db-id :name "T" :schema nil :active true}- :model/Field _ {:table_id table-id :name "ID" :base_type :type/Integer}]- (let [filtering-on (fn [db schema table field]- (edit-file (shop (question-resources)) question-path- #(assoc % :database_id db- :dataset_query {:database db- :lib/type "mbql/query"- :stages [{:lib/type "mbql.stage/mbql"- :source-table [db schema table]- :filters [["=" {} ["field" {} [db schema table field]] 1]]}]})))]- (is (= [] (messages (filtering-on "no-schemas" nil "T" "NOPE"))))- (is (some #(str/includes? % "NOPE") (warnings (filtering-on "no-schemas" nil "T" "NOPE"))))- (is (= [] (warnings (filtering-on "no-schemas" nil "T" "ID"))))- (is (some #(str/includes? % "NOPE") (warnings (filtering-on (:name (mt/db)) "PUBLIC" "VENUES" "NOPE"))))))))--(deftest warns-of-a-table-or-field-named-in-any-reference-test- (testing "serialization makes a placeholder for a missing table or field wherever a file references one, and the pull- logs it"- (let [db (:name (mt/db))- refused (fn [missing f]- (let [tree (edit-file (shop (question-resources)) question-path f)]- (is (= [] (messages tree)) missing)- (is (some #(str/includes? % missing) (warnings tree)) missing)))]- (testing "result metadata"- (refused "NOPE_META" #(assoc % :result_metadata [{:name "NOPE"- :base_type "type/Text"- :id [db "PUBLIC" "VENUES" "NOPE_META"]}])))- (testing "the source field of a field reference"- (refused "NOPE_SOURCE" #(assoc-in % [:dataset_query :stages 0 :fields]- [["field" {:source-field [db "PUBLIC" "VENUES" "NOPE_SOURCE"]}- [db "PUBLIC" "VENUES" "ID"]]])))- (testing "a field reference in the older form"- (refused "NOPE_LEGACY" #(assoc-in % [:dataset_query :stages 0 :filters]- [["=" {} ["field" [db "PUBLIC" "VENUES" "NOPE_LEGACY"] nil] 1]])))- (testing "a table template tag"- (refused "NOPE_TAG_TABLE" #(assoc % :dataset_query- {:database db- :lib/type "mbql/query"- :stages [{:lib/type "mbql.stage/native"- :native "SELECT * FROM {{t}}"- :template-tags {"t" {:type "table"- :name "t"- :display-name "T"- :id "7f2c2a0e-6c1e-4b53-9d0a-0d5a3a1d1c12"- :table-id [db "PUBLIC" "NOPE_TAG_TABLE"]}}}]})))- (testing "a list of strings that isn't a reference is left alone, even when it starts with a database's name"- (is (= [] (warnings (edit-file (shop (question-resources)) question-path- #(assoc % :visualization_settings {:some.custom/labels [db "Alpha" "Beta"]}))))))- (testing "and a file that names only what exists has nothing to log"- (is (= [] (warnings (shop (question-resources)))))))))--(deftest accepts-a-database-the-instance-does-not-have-yet-test- (testing "a query on a database that isn't connected yet loads as a card's does, against a stub database that a- later connection and sync fill in"- (let [tree (edit-file (shop (question-resources)) question-path- #(-> %- (assoc :database_id "Not connected yet")- (assoc-in [:dataset_query :database] "Not connected yet")- (assoc-in [:dataset_query :stages 0 :source-table] ["Not connected yet" "analytics" "accounts"])))]- (is (= [] (messages tree)))- (is (some #(str/includes? % "references table [\"Not connected yet\" \"analytics\" \"accounts\"], which does not exist")- (warnings tree))))))--(deftest refuses-more-of-what-a-resource-may-not-hold-test- (let [refused (fn [tree message]- (is (some #(str/includes? % message) (messages tree)) message))- tree (fn [] (shop (question-resources)))]- (testing "a collection file that isn't a root collection of the data-apps namespace"- (doseq [change [{:parent_id "someOtherCollection01"} {:archived true} {:is_remote_synced true}- {:authority_level "official"} {:type "instance-analytics"}]]- (refused (edit-file (tree) collection-path #(merge % change))- "must be a root collection that is not remote-synced or archived"))- (doseq [change [{:namespace "snippets"} {:namespace nil}]]- (refused (edit-file (tree) collection-path #(merge % change))- "must be in the data-apps collection namespace")))- (testing "a card that belongs to a dashboard or a document"- (refused (edit-file (tree) question-path #(assoc % :dashboard_id "someDashboardEntity01"))- "must not belong to a dashboard or document")- (refused (edit-file (tree) question-path #(assoc % :document_id "someDocumentEntityI01"))- "must not belong to a dashboard or document"))- (testing "an embedded card"- (refused (edit-file (tree) question-path #(assoc % :enable_embedding true))- "must not be public or embedded"))- (testing "a snippet that the instance doesn't have"- (refused (edit-file (tree) question-path- #(assoc % :dataset_query- {:database (:database (:dataset_query %))- :lib/type "mbql/query"- :stages [{:lib/type "mbql.stage/native"- :native "SELECT 1 {{snippet: s}}"- :template-tags {"snippet: s" {:type "snippet"- :name "snippet: s"- :display-name "Snippet: s"- :id "7f2c2a0e-6c1e-4b53-9d0a-0d5a3a1d1c13"- :snippet-name "s"- :snippet-id "nowhereSnippetEid0000"}}}]}))- "references NativeQuerySnippet nowhereSnippetEid0000, which does not exist on this instance"))- (testing "one card defined by two files"- (let [resources (question-resources)- path (some #(when (str/includes? % question-eid) %) (keys resources))]- (refused (shop (assoc resources (str collection-dir "copy.yaml") (get resources path)))- "is defined by more than one file")))))--(deftest refuses-an-action-that-takes-its-parameter-values-from-a-card-test- (data-apps.tu/do-with-sources!- (fn [{:keys [action-id]}]- (let [resources (data-apps.tu/build-resources- collection-name collection-eid- [{:entity_id question-eid :name "VenuesList" :query (venues-query)}]- [action-id])- tree (edit-file (shop resources) action-path- #(assoc % :parameters [{:id "name" :slug "name" :type "string/="- :values_source_config {:card_id question-eid}}]))]- (is (some #(str/includes? % "must not take parameter values from a card") (messages tree)))))))--(deftest refuses-a-reference-by-numeric-id-test- (testing "a numeric ID names a row on one instance, and slips past the checks that read entity IDs"- (mt/with-temp [:model/Card {other-id :id} {:dataset_query {:database (mt/id)- :type :query- :query {:source-table (mt/id :venues)}}}]- (let [refused (fn [f]- (is (some #(str/includes? % "numeric ID")- (messages (edit-file (shop (question-resources)) question-path f)))))- native (fn [tag]- #(assoc % :dataset_query {:database (:database (:dataset_query %))- :lib/type "mbql/query"- :stages [{:lib/type "mbql.stage/native"- :native "SELECT * FROM {{t}}"- :template-tags {"t" (merge {:name "t" :display-name "T"- :id "7f2c2a0e-6c1e-4b53-9d0a-0d5a3a1d1c12"}- tag)}}]}))]- (testing "a card"- (refused #(update % :dataset_query assoc :stages [{:lib/type "mbql.stage/mbql" :source-card other-id}])))- (testing "a table"- (refused #(assoc-in % [:dataset_query :stages 0 :source-table] (mt/id :venues))))- (testing "a field"- (refused #(assoc-in % [:dataset_query :stages 0 :filters] [["=" {} ["field" {} (mt/id :venues :id)] 1]])))- (testing "a field in the older form"- (refused #(assoc-in % [:dataset_query :stages 0 :filters] [["=" {} ["field" (mt/id :venues :id) nil] 1]])))- (testing "a card template tag"- (refused (native {:type "card" :card-id other-id})))- (testing "a snippet template tag"- (refused (native {:type "snippet" :snippet-name "s" :snippet-id 1})))- (testing "a table template tag"- (refused (native {:type "table" :table-id (mt/id :venues)})))))))--(deftest refuses-more-references-by-numeric-id-test- (testing "a card as the source table in the older form, the source field of a field reference, and a database"- (mt/with-temp [:model/Card {other-id :id} {:dataset_query {:database (mt/id)- :type :query- :query {:source-table (mt/id :venues)}}}]- (let [refused (fn [f]- (is (some #(str/includes? % "numeric ID")- (messages (edit-file (shop (question-resources)) question-path f)))))]- (refused #(assoc-in % [:dataset_query :stages 0 :source-table] (str "card__" other-id)))- (refused #(assoc-in % [:dataset_query :stages 0 :fields]- [["field" {:source-field (mt/id :venues :category_id)} "NAME"]]))- (refused #(assoc-in % [:dataset_query :database] (mt/id)))))))--(deftest refuses-a-change-of-the-apps-collection-test- (testing "the app's hooks refuse a change of collection, but only after the load has moved what it reached first"- (mt/with-temp [:model/Collection {collection-id :id} {:entity_id collection-eid :name "Mine" :namespace :data-apps}- :model/DataApp _ {:name "shop" :display_name "Shop" :bundle_path "index.js"- :entity_id (data-apps.tu/app-entity-id "shop")- :resource_collection_id collection-id}]- (let [other-eid (data-apps.tu/collection-entity-id "other")- resources (data-apps.tu/build-resources collection-name other-eid- [{:entity_id question-eid :name "VenuesList" :query (venues-query)}]- [])]- (is (some #(str/includes? % "a data app's collection cannot be changed")- (messages (shop resources :collection other-eid))))- (testing "the collection the app has is fine"- (is (= [] (messages (shop (question-resources))))))))))--(deftest refuses-a-manifest-that-doesnt-say-what-it-is-test- (testing "a data_app.yaml without serdes/meta would be skipped by the load, and the app deleted as no longer in the- repository"- (is (some #(str/includes? % "must hold a single DataApp whose serdes/meta ID is its entity_id")- (messages (edit-file (shop nil) "data_apps/shop/data_app.yaml" #(dissoc % :serdes/meta)))))))--(deftest refuses-two-manifests-with-one-entity-id-test- (testing "a load keeps one app, and the other's collection is left with no owner"- (let [tree (merge (shop (question-resources))- (data-apps.tu/app-files "shop2" {:name "Shop 2" :path "index.js" :bundle "B"- :entity_id (data-apps.tu/app-entity-id "shop")}))]- (is (= 2 (count (filter #(str/includes? % "which another data app also has") (messages tree))))))))--(deftest refuses-a-manifest-whose-slug-an-app-made-here-has-test- (testing "an app made on the instance keeps its slug, and a load would refuse the repository's app only after its- collection and cards had loaded"- (mt/with-temp [:model/DataApp _ {:name "shop" :display_name "Shop" :bundle_path "index.js"- :entity_id "madeHereAppEntity0001"}]- (is (some #(str/includes? % "a data app made on this instance already has")- (messages (shop (question-resources))))))))--(deftest refuses-two-manifests-with-one-slug-test- (testing "a load keeps the first app and refuses the second after it has started"- (let [tree (merge (shop (question-resources))- (edit-file (data-apps.tu/app-files "shop2" {:name "Shop 2" :path "index.js" :bundle "B"})- "data_apps/shop2/data_app.yaml" #(assoc % :slug "shop")))]- (is (= 2 (count (filter #(str/includes? % "has the slug") (messages tree))))))))--(deftest lists-a-problem-two-apps-find-once-test- (testing "two apps that name one collection each find the problems of its files, which are listed once"- (let [app (fn [slug] (data-apps.tu/app-files slug {:name slug :path "index.js" :bundle "B" :collection collection-eid}))- found (messages (merge (app "first") (app "second")))]- (is (= 1 (count (filter #(str/includes? % "is defined by more than one file") found))))- (is (apply distinct? found)))))--(deftest refuses-other-content-in-the-apps-collection-test- (testing "a data app's collection holds cards and actions only, and a load would refuse anything else only after it- had started"- (let [tree (assoc (shop (question-resources))- (str collection-dir "launches.yaml")- (yaml/generate-string {:name "Launches"- :entity_id "shopTimelineLaunches0"- :collection_id collection-eid- :serdes/meta [{:model "Timeline" :id "shopTimelineLaunches0"}]}))]- (is (some #(str/includes? % "holds only questions, metrics and query actions") (messages tree))))))--(deftest accepts-what-a-failed-pull-left-in-the-collection-the-app-claims-test- (testing "a card loaded into the app's collection before the app itself failed to load is the app's to claim"- (mt/with-temp [:model/Collection {collection-id :id} {:entity_id collection-eid :name "Mine" :namespace :data-apps}- :model/Card _ {:name "Left behind" :entity_id question-eid :collection_id collection-id}]- (is (= [] (messages (shop (question-resources)))))- (testing "but not one in another collection of the namespace"- (mt/with-temp [:model/Collection {other-id :id} {:name "Other" :namespace :data-apps}]- (t2/update! :model/Card :entity_id question-eid {:collection_id other-id})- (is (some #(str/includes? % "already exists outside this data app's collection")- (messages (shop (question-resources))))))))))--(deftest warns-of-a-table-that-is-inactive-test- (testing "an inactive table is one that sync no longer finds, or a placeholder a load made, so the pull logs it"- (let [resources (question-resources)]- (mt/with-temp-vals-in-db :model/Table (mt/id :venues) {:active false}- (is (= [] (messages (shop resources))))- (is (some #(str/includes? % "references table [") (warnings (shop resources))))))))--(deftest warns-of-a-field-that-is-inactive-test- (testing "an inactive field is one that sync no longer finds: one column isn't the app, so the file loads and the- pull logs the field rather than refusing the repository until the file changes"- (let [resources (data-apps.tu/build-resources- collection-name collection-eid- [{:entity_id question-eid :name "VenuePrices"- :query {:stages [{:source {:type "table" :id (mt/id :venues)}- :fields [{:type "column" :name "PRICE"}]}]}}]- [])]- (mt/with-temp-vals-in-db :model/Field (mt/id :venues :price) {:active false}- (is (= [] (messages (shop resources))))- (is (some #(str/includes? % "references field") (warnings (shop resources)))))- (testing "an active field is nothing to log"- (is (= [] (warnings (shop resources))))))))--(deftest refuses-a-collection-inside-the-apps-collection-test- (testing "a data app's collection holds no collections, and a load would refuse one only after it had started"- (let [inner "innerCollectionEnt01"- tree (assoc (shop (question-resources))- (str collection-dir "inner.yaml")- (yaml/generate-string {:serdes/meta [{:model "Collection" :id inner :label "inner"}]- :entity_id inner- :name "Inner"- :namespace "data-apps"- :parent_id collection-eid}))]- (is (some #(str/includes? % "is a collection inside a data app's collection") (messages tree))))))--(deftest accepts-the-collection-files-of-an-app-the-commit-no-longer-holds-test- (testing "the files of a collection no manifest names, what a deleted app's directory leaves behind, don't fail the- pull: it deletes the app, whose hook deletes the collection, and the next export removes the files"- (let [tree (dissoc (shop (question-resources)) "data_apps/shop/data_app.yaml" "data_apps/shop/index.js")]- (is (= [] (messages tree))))))diff --git a/enterprise/backend/test/metabase_enterprise/data_apps/resources_test.clj b/enterprise/backend/test/metabase_enterprise/data_apps/resources_test.cljindex 7e2d35eed00..f37a3067107 100644--- a/enterprise/backend/test/metabase_enterprise/data_apps/resources_test.clj+++ b/enterprise/backend/test/metabase_enterprise/data_apps/resources_test.clj@@ -3,6 +3,7 @@[clojure.test :refer :all][metabase-enterprise.data-apps.group-access :as group-access][metabase-enterprise.data-apps.resources :as data-app.resources]+ [metabase-enterprise.data-apps.test-util :as data-apps.tu][metabase.collections.models.collection :as collection][metabase.permissions.core :as perms][metabase.test :as mt]@@ -40,21 +41,22 @@;; The app collection is readable by its own group alone, so only an admin;; can put the copy there.(mt/with-test-user :crowberto- (mt/with-temp [:model/Card {card-id :id} {:collection_id resource_collection_id}]- ;; a data app's collection can no longer be trashed, so trash it as an instance from before that rule did- (mt/with-dynamic-fn-redefs [perms/data-app-collection? (constantly false)]- (collection/archive-or-unarchive-collection!- (t2/select-one :model/Collection :id resource_collection_id)- {:archived true}))- (is (true? (t2/select-one-fn :archived :model/Collection :id resource_collection_id))- "precondition: the collection is in the trash")- (is (true? (t2/select-one-fn :archived :model/Card :id card-id))- "precondition: trashing the collection archived the copy")- (data-app.resources/ensure-resources! (t2/select-one :model/DataApp :id (:id app)))- (is (false? (t2/select-one-fn :archived :model/Collection :id resource_collection_id))- "the app collection is out of the trash")- (is (false? (t2/select-one-fn :archived :model/Card :id card-id))- "the copy the app serves is readable again")))))))+ (data-apps.tu/with-published-tables! [(mt/id :venues)]+ (mt/with-temp [:model/Card {card-id :id} {:collection_id resource_collection_id :dataset_query (data-apps.tu/venues-query)}]+ ;; a data app's collection can no longer be trashed, so trash it as an instance from before that rule did+ (mt/with-dynamic-fn-redefs [perms/data-app-collection? (constantly false)]+ (collection/archive-or-unarchive-collection!+ (t2/select-one :model/Collection :id resource_collection_id)+ {:archived true}))+ (is (true? (t2/select-one-fn :archived :model/Collection :id resource_collection_id))+ "precondition: the collection is in the trash")+ (is (true? (t2/select-one-fn :archived :model/Card :id card-id))+ "precondition: trashing the collection archived the copy")+ (data-app.resources/ensure-resources! (t2/select-one :model/DataApp :id (:id app)))+ (is (false? (t2/select-one-fn :archived :model/Collection :id resource_collection_id))+ "the app collection is out of the trash")+ (is (false? (t2/select-one-fn :archived :model/Card :id card-id))+ "the copy the app serves is readable again"))))))))(deftest ensure-resources-recreates-a-deleted-collection-test(testing "the reference is nullable so the collection can be deleted on its own; the next import gives the appdiff --git a/enterprise/backend/test/metabase_enterprise/data_apps/serialization_test.clj b/enterprise/backend/test/metabase_enterprise/data_apps/serialization_test.cljindex 79d6db89b5c..df5e1bdcc61 100644--- a/enterprise/backend/test/metabase_enterprise/data_apps/serialization_test.clj+++ b/enterprise/backend/test/metabase_enterprise/data_apps/serialization_test.clj@@ -3,6 +3,7 @@[clojure.java.io :as io][clojure.test :refer :all][metabase-enterprise.data-apps.group-access :as group-access]+ [metabase-enterprise.data-apps.test-util :as data-apps.tu][metabase-enterprise.serialization.core :as serialization][metabase-enterprise.serialization.test-util :as ts][metabase-enterprise.serialization.v2.extract :as extract]@@ -209,30 +210,31 @@(deftest round-trip-with-resources-test(testing "an app travels with its collection and what that holds, written under collections/data_apps/"(mt/with-premium-features #{:data-apps}- (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup :model/Card :model/Action]- (ts/with-random-dump-dir [dump-dir "data-app-resources-"]- (let [app (insert-app!)- collection-id (:resource_collection_id app)- mp (mt/metadata-provider)- query (lib/query mp (lib.metadata/table mp (mt/id :venues)))]- (mt/with-temp [:model/Card {question-eid :entity_id} {:name "Venues list" :type :question- :collection_id collection-id :dataset_query query}]- (let [action-id (actions/insert! {:name "Rename venue"- :type :query- :collection_id collection-id- :database_id (mt/id)- :dataset_query (lib/native-query mp "UPDATE venues SET name = 'x'")})- action-eid (t2/select-one-fn :entity_id :model/Action :id action-id)]- (export! dump-dir :with-collections? true)- (testing "the files sit under the collection's directory of the data-apps namespace"- (doseq [path ["data_app__sales_ops.yaml" "data_app__sales_ops/venues_list.yaml"- "data_app__sales_ops/rename_venue.yaml"]]- (is (.exists (io/file dump-dir "collections" "data_apps" path)) path)))- (t2/delete! :model/DataApp (:id app))- (is (not (t2/exists? :model/Card :entity_id question-eid)) "deleting the app deletes its collection's cards")- (import! dump-dir)- (let [imported (t2/select-one :model/DataApp :entity_id (:entity_id app))- collection-id (:resource_collection_id imported)]- (is (pos-int? collection-id))- (is (= collection-id (t2/select-one-fn :collection_id :model/Card :entity_id question-eid)))- (is (= collection-id (t2/select-one-fn :collection_id :model/Action :entity_id action-eid))))))))))))+ (data-apps.tu/with-published-tables! [(mt/id :venues)]+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup :model/Card :model/Action]+ (ts/with-random-dump-dir [dump-dir "data-app-resources-"]+ (let [app (insert-app!)+ collection-id (:resource_collection_id app)+ mp (mt/metadata-provider)+ query (lib/query mp (lib.metadata/table mp (mt/id :venues)))]+ (mt/with-temp [:model/Card {question-eid :entity_id} {:name "Venues list" :type :question+ :collection_id collection-id :dataset_query query}]+ (let [action-id (actions/insert! {:name "Rename venue"+ :type :query+ :collection_id collection-id+ :database_id (mt/id)+ :dataset_query (lib/native-query mp "UPDATE venues SET name = 'x'")})+ action-eid (t2/select-one-fn :entity_id :model/Action :id action-id)]+ (export! dump-dir :with-collections? true)+ (testing "the files sit under the collection's directory of the data-apps namespace"+ (doseq [path ["data_app__sales_ops.yaml" "data_app__sales_ops/venues_list.yaml"+ "data_app__sales_ops/rename_venue.yaml"]]+ (is (.exists (io/file dump-dir "collections" "data_apps" path)) path)))+ (t2/delete! :model/DataApp (:id app))+ (is (not (t2/exists? :model/Card :entity_id question-eid)) "deleting the app deletes its collection's cards")+ (import! dump-dir)+ (let [imported (t2/select-one :model/DataApp :entity_id (:entity_id app))+ collection-id (:resource_collection_id imported)]+ (is (pos-int? collection-id))+ (is (= collection-id (t2/select-one-fn :collection_id :model/Card :entity_id question-eid)))+ (is (= collection-id (t2/select-one-fn :collection_id :model/Action :entity_id action-eid)))))))))))))diff --git a/enterprise/backend/test/metabase_enterprise/data_apps/test_util.clj b/enterprise/backend/test/metabase_enterprise/data_apps/test_util.cljindex f83ae1932d6..dc77dad4306 100644--- a/enterprise/backend/test/metabase_enterprise/data_apps/test_util.clj+++ b/enterprise/backend/test/metabase_enterprise/data_apps/test_util.clj@@ -1,6 +1,8 @@(ns metabase-enterprise.data-apps.test-util(:require+ [clojure.set :as set][clojure.string :as str]+ [metabase-enterprise.data-studio.db :as data-studio.db][metabase-enterprise.serialization.core :as serialization][metabase-enterprise.serialization.dump :as serialization.dump][metabase.actions.core :as actions]@@ -9,7 +11,6 @@[metabase.lib.core :as lib][metabase.lib.metadata :as lib.metadata][metabase.models.serialization :as serdes]- [metabase.models.serialization.resolve :as resolve][metabase.test :as mt][metabase.util.yaml :as yaml][toucan2.core :as t2])@@ -113,16 +114,6 @@:authority_level nil :archived false :archived_directly false :archive_operation_id nil:is_remote_synced false :is_sample false :personal_owner_id nil :created_at nil})-(defn- copy-overriding-resolver [base card-id->copy-entity-id]- (reify resolve/SerdesExportResolver- (export-fk [_ id model]- (or (when (= "Card" (name model)) (card-id->copy-entity-id id))- (resolve/export-fk base id model)))- (export-fk-keyed [_ id model field] (resolve/export-fk-keyed base id model field))- (export-user [_ id] (resolve/export-user base id))- (export-table-fk [_ id] (resolve/export-table-fk base id))- (export-field-fk [_ id] (resolve/export-field-fk base id))))-(defn- file-path"The repo path of an entity of the collection named `collection-name`: the collection's own file, or a file in thecollection's directory named after the entity, with its entity ID so a test can find it."@@ -135,59 +126,29 @@(defn build-resources"The files an author commits for the collection named `collection-name` with `collection-entity-id`, keyed by theirrepo path under `collections/data_apps/`: the collection, a saved question per `{:entity_id :name :query}` in- `queries`, and copies of the metrics those use and of the actions with `action-ids`, which belong to no model.- Copies get [[copy-entity-id]]s."+ `queries`, which names the Library metrics it uses by their own entity IDs, and copies of the actions with+ `action-ids`, which belong to no model. Copies get [[copy-entity-id]]s."[collection-name collection-entity-id queries action-ids](let [resolved (for [{:keys [query] :as spec} queries:let [table-id (get-in query [:stages 0 :source :id])mp (lib-be/application-database-metadata-provider(t2/select-one-fn :db_id :model/Table :id table-id))]]{:spec spec :query (lib/test-query mp query)})- metrics (t2/select :model/Card :id [:in (into #{-1} (mapcat (comp lib/all-source-card-ids :query)) resolved)])actions (map #(t2/select-one :model/Action :id %) action-ids)- copy-id (fn [kind source] (copy-entity-id kind collection-entity-id (:entity_id source)))- copy-ids (into {} (map (juxt :id (partial copy-id "metric"))) metrics)+ copy-id (fn [action] (copy-entity-id "action" collection-entity-id (:entity_id action)))extract (fn [model-name instance](cond-> (serdes/extract-one model-name {} instance)(not= "Collection" model-name) (assoc :collection_id collection-entity-id)))entities (serdes/with-cache- (binding [resolve/*export-resolver* (copy-overriding-resolver resolve/*export-resolver* copy-ids)]- (doall- (concat- [(extract "Collection" (collection collection-entity-id collection-name))]- (for [{:keys [spec query]} resolved]- (extract "Card" (question spec query)))- (for [card metrics]- (extract "Card" (merge card instance-fields {:entity_id (copy-ids (:id card))- :creator_id (mt/user->id :crowberto)})))- (for [action actions]- (extract "Action" (action-copy action (copy-id "action" action))))))))]+ (doall+ (concat+ [(extract "Collection" (collection collection-entity-id collection-name))]+ (for [{:keys [spec query]} resolved]+ (extract "Card" (question spec query)))+ (for [action actions]+ (extract "Action" (action-copy action (copy-id action)))))))](into (sorted-map) (map (juxt (partial file-path collection-name) serialization.dump/yaml-content)) entities)))-(defn do-with-sources!- "Call `f` with the sources a data app copies, a venues metric and a query action that belongs to no model, and with- what it can't copy, a venues model and an action on it, as `{:metric-id :action-id :model-id :model-action-id}`."- [f]- (let [mp (mt/metadata-provider)- query (lib/query mp (lib.metadata/table mp (mt/id :venues)))]- (mt/with-temp [:model/Card {metric-id :id} {:name "Venue count"- :type :metric- :database_id (mt/id)- :dataset_query (lib/aggregate query (lib/count))}- :model/Card {model-id :id} {:name "Venues model"- :type :model- :database_id (mt/id)- :dataset_query query}]- (f {:metric-id metric-id- :action-id (actions/insert! {:name "Rename venue"- :type :query- :database_id (mt/id)- :dataset_query (lib/native-query mp "UPDATE venues SET name = {{name}}")- :parameters [{:id "name" :slug "name" :type :string/=}]})- :model-id model-id- :model-action-id (actions/insert! {:name "Create venue" :type :implicit :kind :row/create- :model_id model-id})}))))-(defn do-with-library!"Call `f` with the IDs of the root data library (`:data-id`) and metrics library (`:metrics-id`) collections, creating thelibrary for the call when the instance has none."@@ -202,3 +163,65 @@(finally(when-not existing(t2/delete! :model/Collection :id [:in (cons (:id library) (map :id children))]))))))++(defn do-with-sources!+ "Call `f` with what a data app uses from outside its collection, a venues metric in the Library and a query action+ that belongs to no model, and with what it can't, a venues model and an action on it, as+ `{:metric-id :action-id :model-id :model-action-id}`."+ [f]+ (do-with-library!+ (fn [{:keys [metrics-id]}]+ (let [mp (mt/metadata-provider)+ query (lib/query mp (lib.metadata/table mp (mt/id :venues)))]+ (mt/with-temp [:model/Card {metric-id :id} {:name "Venue count"+ :type :metric+ :collection_id metrics-id+ :database_id (mt/id)+ :dataset_query (lib/aggregate query (lib/count))}+ :model/Card {model-id :id} {:name "Venues model"+ :type :model+ :database_id (mt/id)+ :dataset_query query}]+ (f {:metric-id metric-id+ :action-id (actions/insert! {:name "Rename venue"+ :type :query+ :database_id (mt/id)+ :dataset_query (lib/native-query mp "UPDATE venues SET name = {{name}}")+ :parameters [{:id "name" :slug "name" :type :string/=}]})+ :model-id model-id+ :model-action-id (actions/insert! {:name "Create venue" :type :implicit :kind :row/create+ :model_id model-id})}))))))++(defn venues-query+ "A query of the VENUES table, which a card in a data app's collection may read once it is published."+ []+ (let [mp (mt/metadata-provider)]+ (lib/query mp (lib.metadata/table mp (mt/id :venues)))))++(defn do-with-published-tables!+ "Call `f` with the Tables with `table-ids` published to the Library's Data collection, as a card in a data app's+ collection needs the tables it reads, putting back afterwards the published state of only the ones this call+ published, which drops a user settings row left empty, and creating the Library for the call when the instance has+ none."+ [table-ids f]+ (do-with-library!+ (fn [{:keys [data-id]}]+ (let [to-publish (set/difference (set table-ids) (data-studio.db/published-table-ids (set table-ids)))+ previous (when (seq to-publish)+ (into {}+ (map (juxt :table_id #(select-keys % [:collection_id :is_published])))+ (t2/select [:model/TableUserSettings :table_id :collection_id :is_published]+ :table_id [:in to-publish])))]+ (when (seq to-publish)+ (data-studio.db/publish-tables! to-publish data-id))+ (try+ (f)+ (finally+ (doseq [table-id to-publish]+ (t2/update! :model/TableUserSettings :table_id table-id+ (get previous table-id {:collection_id nil, :is_published nil})))))))))++(defmacro with-published-tables!+ "Run `body` with the Tables with `table-ids` published to the Library."+ [table-ids & body]+ `(do-with-published-tables! ~table-ids (fn [] ~@body)))diff --git a/enterprise/backend/test/metabase_enterprise/remote_sync/data_apps_test.clj b/enterprise/backend/test/metabase_enterprise/remote_sync/data_apps_test.cljindex ca169561cec..72d1605ed92 100644--- a/enterprise/backend/test/metabase_enterprise/remote_sync/data_apps_test.clj+++ b/enterprise/backend/test/metabase_enterprise/remote_sync/data_apps_test.clj@@ -14,7 +14,6 @@[metabase-enterprise.remote-sync.test-helpers :as test-helpers][metabase.actions.core :as actions][metabase.collections.models.collection :as collection]- [metabase.events.core :as events][metabase.lib.core :as lib][metabase.lib.metadata :as lib.metadata][metabase.permissions.core :as perms]@@ -75,7 +74,9 @@(mt/with-temporary-setting-values [remote-sync-type :read-write remote-sync-enabled true remote-sync-transforms false];; the cleanup deletes without hooks, so what a pull loads into an app's collection is listed too(mt/with-model-cleanup [:model/DataApp :model/Action :model/Card :model/Collection :model/PermissionsGroup]- ~@body)))))+ ;; a card in an app's collection reads only tables published to the Library+ (data-apps.tu/with-published-tables! [(mt/id :venues) (mt/id :checkins)]+ ~@body))))))(deftest pull-imports-and-prunes-data-apps-test(with-data-apps-sync@@ -178,14 +179,11 @@(def ^:private question-eid "shopQuestionListVenue")-(defn- venues-query []+(defn- venues-stages []{:stages [{:source {:type "table" :id (mt/id :venues)} :limit 5}]})(def ^:private shop-collection-name "Data App: shop")-(def ^:private shop-collection-dir- (str "collections/data_apps/" (data-apps.tu/collection-dir shop-collection-name) "/"))-(defn- shop-tree"The repo files of the `shop` app with `resources` (see `data-apps.tu/build-resources`), the resources under`collections/data_apps/data_app__shop/`."@@ -203,14 +201,14 @@(fn [{:keys [metric-id action-id]}](let [resources (data-apps.tu/build-resourcesshop-collection-name shop-collection-eid- [{:entity_id question-eid :name "VenuesList" :query (venues-query)}+ [{:entity_id question-eid :name "VenuesList" :query (venues-stages)}{:entity_id "shopQuestionMetricVen" :name "VenueCount":query {:stages [{:source {:type "table" :id (mt/id :venues)}:aggregations [{:type "metric" :id metric-id}]}]}}][action-id])src (test-helpers/versioned-source :trees {"v0" (shop-tree resources)} :current "v0")- copy-eid (fn [kind source-model source-id]- (data-apps.tu/copy-entity-id kind shop-collection-eid (t2/select-one-fn :entity_id source-model :id source-id)))]+ copy-eid (fn [action-id]+ (data-apps.tu/copy-entity-id "action" shop-collection-eid (t2/select-one-fn :entity_id :model/Action :id action-id)))](let [result (import-at! src "v0" :force? true)](is (= :success (:status result)) (:message result)))(let [collection-id (shop-collection-id)]@@ -219,20 +217,22 @@(testing "each query is a saved question in the collection"(is (=? {:type :question :name "VenuesList" :collection_id collection-id}(t2/select-one :model/Card :entity_id question-eid))))- (testing "the metric a query uses is copied"- (is (=? {:type :metric :collection_id collection-id}- (t2/select-one :model/Card :entity_id (copy-eid "metric" :model/Card metric-id)))))+ (testing "a query aggregates the Library metric itself, which stays in the Library"+ (let [card (t2/select-one :model/Card :entity_id "shopQuestionMetricVen")]+ (is (= [metric-id] (vec (lib/all-metric-ids (lib/query (mt/metadata-provider) (:dataset_query card)))))))+ (is (not= collection-id (t2/select-one-fn :collection_id :model/Card :id metric-id)))+ (is (not (t2/exists? :model/Card :collection_id collection-id :type :metric))))(testing "the action is copied into the collection, on no model"(is (=? {:type :query :collection_id collection-id :model_id nil}- (t2/select-one :model/Action :entity_id (copy-eid "action" :model/Action action-id)))))+ (t2/select-one :model/Action :entity_id (copy-eid action-id)))))(testing "the source is untouched"(is (nil? (t2/select-one-fn :collection_id :model/Action :id action-id)))))))))))(deftest pull-updates-and-removes-resources-with-their-files-test(with-data-apps-sync(let [resources (data-apps.tu/build-resources shop-collection-name shop-collection-eid- [{:entity_id question-eid :name "VenuesList" :query (venues-query)}- {:entity_id "shopQuestionOther0001" :name "Other" :query (venues-query)}]+ [{:entity_id question-eid :name "VenuesList" :query (venues-stages)}+ {:entity_id "shopQuestionOther0001" :name "Other" :query (venues-stages)}][])file-of (fn [eid] (some #(when (str/includes? % eid) %) (keys resources)))renamed (update resources (file-of question-eid) #(yaml/generate-string (assoc (yaml/parse-string %) :name "Renamed")))@@ -252,35 +252,18 @@(is (not (t2/exists? :model/Card :entity_id "shopQuestionOther0001"))))))))(deftest pull-refuses-resources-an-app-may-not-hold-test- (testing "a resource file a load can't take as meant fails the pull, naming the file, before anything loads"+ (testing "a resource the Card hook refuses fails the pull"(with-data-apps-sync(let [resources (data-apps.tu/build-resources shop-collection-name shop-collection-eid- [{:entity_id question-eid :name "VenuesList" :query (venues-query)}]+ [{:entity_id question-eid :name "VenuesList" :query (venues-stages)}][])card-file (some #(when (str/includes? % question-eid) %) (keys resources))archived (update resources card-file #(yaml/generate-string (assoc (yaml/parse-string %) :archived true)))src (test-helpers/versioned-source :trees {"v0" (shop-tree archived)} :current "v0")result (import-at! src "v0" :force? true)](is (= :error (:status result)))- (is (str/includes? (:message result) card-file))- (testing "nothing loaded"- (is (not (t2/exists? :model/DataApp :name "shop")))- (is (not (t2/exists? :model/Collection :entity_id shop-collection-eid)))- (is (not (t2/exists? :model/Card :entity_id question-eid))))))))--(deftest pull-refuses-to-take-over-a-card-elsewhere-test- (testing "a file naming the entity ID of a card outside the app can't move it into the app's collection"- (with-data-apps-sync- (mt/with-temp [:model/Card {foreign-id :id} {:name "Someone else's" :entity_id question-eid}]- (let [src (test-helpers/versioned-source- :trees {"v0" (shop-tree (data-apps.tu/build-resources shop-collection-name shop-collection-eid- [{:entity_id question-eid :name "VenuesList" :query (venues-query)}]- []))}- :current "v0")- result (import-at! src "v0" :force? true)]- (is (= :error (:status result)))- (is (str/includes? (:message result) shop-collection-dir))- (is (= "Someone else's" (t2/select-one-fn :name :model/Card :id foreign-id))))))))+ (is (str/includes? (:message result) "not archived"))+ (is (not (t2/exists? :model/Card :entity_id question-eid)))))))(deftest export-writes-an-apps-resources-under-its-collection-test(testing "what an app's collection holds is exported under collections/data_apps/, like any namespace's content"@@ -314,7 +297,7 @@(defn- question-resources [](data-apps.tu/build-resources shop-collection-name shop-collection-eid- [{:entity_id question-eid :name "VenuesList" :query (venues-query)}]+ [{:entity_id question-eid :name "VenuesList" :query (venues-stages)}][]))(defn- resource-files@@ -328,7 +311,7 @@(some #(str/starts-with? (last (str/split % #"/")) stem) (resource-files mock)))(deftest pull-reaches-permission-warnings-test- (testing "once the jobs run after a pull, the warnings list the tables the app's native question and action name"+ (testing "once the jobs run after a pull, the warnings list the tables the app's question and action name"(with-data-apps-sync(mt/with-premium-features #{:data-apps :advanced-permissions :dependencies}(mt/with-no-data-perms-for-all-users!@@ -341,17 +324,9 @@:parameters [{:id "id" :slug "id" :type :number/=}]})resources (data-apps.tu/build-resourcesshop-collection-name shop-collection-eid- [{:entity_id question-eid :name "VenuesList" :query (venues-query)}]+ [{:entity_id question-eid :name "VenuesList" :query (venues-stages)}][action-id])- path (some #(when (str/includes? % question-eid) %) (keys resources))- parsed (yaml/parse-string (get resources path))- native (assoc parsed :dataset_query {:database (:database (:dataset_query parsed))- :lib/type "mbql/query"- :stages [{:lib/type "mbql.stage/native"- :native "select * from Venues"}]})- src (test-helpers/versioned-source- :trees {"v0" (shop-tree (assoc resources path (yaml/generate-string native)))}- :current "v0")+ src (test-helpers/versioned-source :trees {"v0" (shop-tree resources)} :current "v0")result (import-at! src "v0" :force? true)](is (= :success (:status result)) (:message result))(mt/with-temp [:model/PermissionsGroup group {}]@@ -369,7 +344,7 @@(fn [{:keys [action-id]}](let [resources (data-apps.tu/build-resourcesshop-collection-name shop-collection-eid- [{:entity_id question-eid :name "VenuesList" :query (venues-query)}]+ [{:entity_id question-eid :name "VenuesList" :query (venues-stages)}][action-id])src (test-helpers/versioned-source :trees {"v0" (shop-tree resources)} :current "v0")](is (= :success (:status (import-at! src "v0" :force? true))))@@ -415,7 +390,7 @@(with-data-apps-sync(let [resources (fn [card-name](data-apps.tu/build-resources shop-collection-name shop-collection-eid- [{:entity_id question-eid :name card-name :query (venues-query)}]+ [{:entity_id question-eid :name card-name :query (venues-stages)}][]))src (test-helpers/versioned-source :trees {"v0" (shop-tree (resources "VenuesList"))"v1" (shop-tree (resources "Renamed on read-write"))@@ -439,7 +414,10 @@(is (= :success (:status (import-at! src "v0" :force? true))))(let [collection-id (shop-collection-id)card! (fn [card-type]- (mt/with-temp [:model/Card {card-id :id} {:name "Saved here" :type card-type :collection_id collection-id}]+ (mt/with-temp [:model/Card {card-id :id} {:name "Saved here"+ :type card-type+ :collection_id collection-id+ :dataset_query (data-apps.tu/venues-query)}](t2/select-one :model/Card :id card-id)))](is (thrown-with-msg? clojure.lang.ExceptionInfo #"can hold only questions, metrics, and query actions"(mt/with-temp [:model/Dashboard _ {:name "Saved here" :collection_id collection-id}])))@@ -475,9 +453,9 @@(testing "archived, public, or a model"(mt/with-temporary-setting-values [enable-public-sharing true](mt/user-http-request :crowberto :post 400 (str "card/" card-id "/public_link")))- (is (thrown-with-msg? clojure.lang.ExceptionInfo #"must be a question or metric that is not archived"+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"must be a question or metric"(t2/update! :model/Card card-id {:archived true})))- (is (thrown-with-msg? clojure.lang.ExceptionInfo #"must be a question or metric that is not archived"+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"must be a question or metric"(t2/update! :model/Card card-id {:type :model})))(is (=? {:archived false :public_uuid nil :type :question} (t2/select-one :model/Card :id card-id))))(testing "a card that is already public can't be moved in"@@ -485,7 +463,7 @@:dataset_query q:public_uuid (str (random-uuid)):made_public_by_id (mt/user->id :crowberto)}]- (is (thrown-with-msg? clojure.lang.ExceptionInfo #"must be a question or metric that is not archived"+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"must be a question or metric"(t2/update! :model/Card public-id {:collection_id collection-id})))(is (nil? (t2/select-one-fn :collection_id :model/Card :id public-id)))))(testing "the export keeps its file"@@ -496,32 +474,17 @@(mt/with-temp [:model/Card {other-id :id} {:name "Elsewhere"}](mt/user-http-request :crowberto :put 200 (str "card/" other-id) {:archived true}))))))))-(deftest a-pull-moves-cards-out-of-an-apps-collection-test- (testing "a pull whose commit moves a card and the card that reads it out of an app's collection succeeds: the load- moves the card read first, while its reader is still in the collection"+(deftest pull-moves-card-out-of-apps-collection-test+ (testing "a pull whose commit moves a card out of an app's collection, into an ordinary synced collection, succeeds"(with-data-apps-sync- (let [mock (test-helpers/create-mock-source :initial-files {"main" (shop-tree (question-resources))})- mp (mt/metadata-provider)]+ (let [mock (test-helpers/create-mock-source :initial-files {"main" (shop-tree (question-resources))})](is (= :success (:status (import-at! mock "main" :force? true))))- (let [card-id (t2/select-one-pk :model/Card :entity_id question-eid)- reader (first (t2/insert-returning-instances!- :model/Card- {:name "Reads VenuesList"- :display "table"- :visualization_settings {}- :creator_id (mt/user->id :crowberto)- :database_id (mt/id)- :collection_id (shop-collection-id)- :dataset_query (lib/query mp (lib.metadata/card mp card-id))}))- _ (events/publish-event! :event/card-create {:object reader :user-id (mt/user->id :crowberto)})- _ (is (= :success (:status (export! mock))))- synced-eid "shopCardsMovedOutColl"+ (let [synced-eid "shopCardsMovedOutColl"synced-dir (str "collections/" synced-eid "_moved_out/")- moved-eids #{question-eid (:entity_id reader)}- ;; the commit an author pushes: both cards' files in an ordinary synced collection+ ;; the commit an author pushes: the card's file in an ordinary synced collectionmoved-out (reduce-kv (fn [tree path content](let [entity (yaml/parse-string content)]- (if (contains? moved-eids (:entity_id entity))+ (if (= question-eid (:entity_id entity))(assoc tree(str synced-dir "cards/" (last (str/split path #"/")))(yaml/generate-string (assoc entity :collection_id synced-eid)))@@ -530,41 +493,10 @@(test-helpers/generate-collection-yaml synced-eid "Moved out" :is-remote-synced true)}(get @(:files-atom mock) "main"))src (test-helpers/versioned-source :trees {"v1" moved-out} :current "v1")]- (is (= 2 (count (filter #(str/starts-with? % (str synced-dir "cards/")) (keys moved-out)))))(let [result (import-at! src "v1" :force? true)](is (= :success (:status result)) (:message result)))- (is (= #{(t2/select-one-pk :model/Collection :entity_id synced-eid)}- (t2/select-fn-set :collection_id :model/Card :entity_id [:in moved-eids]))))))))--(deftest deleting-an-app-deletes-cards-that-read-each-other-test- (testing "deleting the app deletes its collection with every card in it, readers and read"- (with-data-apps-sync- (let [mock (test-helpers/create-mock-source :initial-files {"main" (shop-tree (question-resources))})- mp (mt/metadata-provider)]- (is (= :success (:status (import-at! mock "main" :force? true))))- (let [card-id (t2/select-one-pk :model/Card :entity_id question-eid)- collection-id (shop-collection-id)- reader-id (t2/insert-returning-pk! :model/Card- {:name "Reads VenuesList"- :display "table"- :visualization_settings {}- :creator_id (mt/user->id :crowberto)- :database_id (mt/id)- :collection_id collection-id- :dataset_query (lib/query mp (lib.metadata/card mp card-id))})]- (mt/user-http-request :crowberto :delete 204 "ee/apps/shop")- (is (not (t2/exists? :model/Collection :id collection-id)))- (is (not (t2/exists? :model/Card :id [:in [card-id reader-id]]))))))))--(deftest a-pull-of-the-commit-already-imported-is-skipped-test- (testing "a pull that would load nothing isn't failed by the state of the instance"- (with-data-apps-sync- (let [src (test-helpers/versioned-source :trees {"v0" (shop-tree (question-resources))} :current "v0")]- (is (= :success (:status (import-at! src "v0" :force? true))))- (t2/update! :model/Card :entity_id question-eid {:collection_id nil})- (is (=? {:status :success :outcome {:kind "pull-skipped"}} (import-at! src "v0")))- (testing "a pull that would load is still refused"- (is (= :error (:status (import-at! src "v0" :force? true)))))))))+ (is (= (t2/select-one-pk :model/Collection :entity_id synced-eid)+ (t2/select-one-fn :collection_id :model/Card :entity_id question-eid))))))))(deftest pull-refuses-two-apps-that-name-one-collection-test(with-data-apps-sync@@ -572,46 +504,10 @@app (fn [slug] (data-apps.tu/app-files slug {:name slug :path "index.js" :bundle "B" :collection shared}))src (test-helpers/versioned-source :trees {"v0" (merge (app "first") (app "second"))} :current "v0")result (import-at! src "v0" :force? true)]- (is (= :error (:status result)))- (is (str/includes? (:message result) "data_apps/first/data_app.yaml"))- (is (str/includes? (:message result) "data_apps/second/data_app.yaml"))- (testing "a problem both apps find in the collection they share is listed once"- (is (apply distinct? (str/split-lines (:message result)))))- (testing "nothing loaded"- (is (not (t2/exists? :model/DataApp :name [:in ["first" "second"]])))- (is (not (t2/exists? :model/Collection :entity_id shared)))))))--(deftest pull-lists-each-problem-on-its-own-line-test- (testing "a pull refusing several apps names each problem's file once, one problem per line"- (with-data-apps-sync- (let [app (fn [slug] (data-apps.tu/app-files slug {:name slug :path "index.js" :bundle "B" :collection nil}))- src (test-helpers/versioned-source :trees {"v0" (merge (app "first") (app "second"))} :current "v0")- result (import-at! src "v0" :force? true)- [lead & problems] (str/split-lines (:message result))]+ (testing "the database refuses the second app on the collection the first owns"(is (= :error (:status result)))- (is (= "Failed to reload from git repository. Invalid data app files:" lead))- (is (= ["- data_apps/first/data_app.yaml must name the app's resource collection as `collection`."- "- data_apps/second/data_app.yaml must name the app's resource collection as `collection`."]- (sort problems)))))))--(deftest pull-refuses-two-apps-that-define-one-card-test- (with-data-apps-sync- (let [app (fn [slug]- (let [collection (data-apps.tu/collection-entity-id slug)]- (data-apps.tu/app-files slug {:name slug :path "index.js" :bundle "B" :collection collection- :resources (data-apps.tu/build-resources- (str "Data App: " slug) collection- [{:entity_id question-eid :name "VenuesList" :query (venues-query)}]- [])})))- src (test-helpers/versioned-source :trees {"v0" (merge (app "first") (app "second"))} :current "v0")- result (import-at! src "v0" :force? true)]- (is (= :error (:status result)))- (is (str/includes? (:message result) "collections/data_apps/data_app__first/"))- (is (str/includes? (:message result) "collections/data_apps/data_app__second/"))- (testing "nothing loaded"- (is (not (t2/exists? :model/Card :entity_id question-eid)))- (is (not (t2/exists? :model/DataApp :name [:in ["first" "second"]])))- (is (not (t2/exists? :model/Collection :entity_id [:in (map data-apps.tu/collection-entity-id ["first" "second"])])))))))+ (is (str/includes? (:message result) "already belongs to another data app"))+ (is (= 1 (t2/count :model/DataApp :name [:in ["first" "second"]])))))))(deftest pull-refuses-a-manifest-that-names-a-collection-it-doesnt-define-test(testing "a manifest with no resource files can't claim a collection that is already here"@@ -624,95 +520,28 @@:current "v0")result (import-at! src "v0" :force? true)](is (= :error (:status result)))- (is (str/includes? (:message result) "data_apps/shop/data_app.yaml"))+ (is (str/includes? (:message result) "must be a top-level collection of data apps"))+ (is (not (t2/exists? :model/DataApp :name "shop")))(is (t2/exists? :model/Collection :id collection-id))(is (t2/exists? :model/Card :id card-id)))))))-(deftest pull-refuses-a-manifest-that-doesnt-parse-test- (testing "a data_app.yaml that holds no map can't say which app it is, so the pull refuses it naming the manifest,- rather than deleting the app as no longer in the repository"- (with-data-apps-sync- (let [v0 (shop-tree (question-resources))- src (test-helpers/versioned-source :trees {"v0" v0- "empty" (assoc v0 "data_apps/shop/data_app.yaml" "")- "list" (assoc v0 "data_apps/shop/data_app.yaml" "- a\n")- "text" (assoc v0 "data_apps/shop/data_app.yaml" "shop\n")}- :current "v0")]- (is (= :success (:status (import-at! src "v0" :force? true))))- (doseq [version ["empty" "list" "text"]]- (testing version- (let [result (import-at! src version)]- (is (= :error (:status result)))- (is (str/includes? (str (:message result)) "data_apps/shop/data_app.yaml must hold a single DataApp")- (:message result))- (is (t2/exists? :model/DataApp :name "shop")))))))))--(defn- export-merged!- "Export to `src` with `merge`, as an instance whose last sync was `base-version` does once the remote has advanced."- [src base-version]- (t2/delete! :model/RemoteSyncTask :sync_task_type "export")- (let [task (new-task! "export")- result (impl/export! (source.p/snapshot src) task "export"- :merge? true :source src :base-snapshot (source.p/snapshot-at src base-version))]- (impl/handle-task-result! result task)- result))--(deftest an-export-that-merges-checks-like-a-pull-test- (with-data-apps-sync- (testing "a remote file that a pull refuses is refused by an export that merges it in"- (mt/with-temp [:model/Collection {elsewhere :id} {:name "Elsewhere"}- :model/Card {foreign-id :id} {:name "Someone else's" :entity_id "foreignCardEntityId00"- :collection_id elsewhere}]- (let [remote (data-apps.tu/build-resources- shop-collection-name shop-collection-eid- [{:entity_id question-eid :name "VenuesList" :query (venues-query)}- {:entity_id "foreignCardEntityId00" :name "Taken" :query (venues-query)}]- [])- src (test-helpers/versioned-source- :trees {"v0" (shop-tree (question-resources)) "v1" (shop-tree remote)}- :current "v1")]- (is (= :success (:status (import-at! src "v0" :force? true))))- (is (= :error (:status (export-merged! src "v0"))))- (is (=? {:name "Someone else's" :collection_id elsewhere}- (t2/select-one :model/Card :id foreign-id))))))))--(deftest pull-loads-a-snippet-with-the-card-that-uses-it-test- (testing "a resource may use a snippet that the same pull brings"- (with-data-apps-sync- (mt/with-model-cleanup [:model/NativeQuerySnippet]- (let [snippet-eid "appSnippetEntityId000"- resources (question-resources)- path (some #(when (str/includes? % question-eid) %) (keys resources))- parsed (yaml/parse-string (get resources path))- native (assoc parsed :dataset_query- {:database (:database (:dataset_query parsed))- :lib/type "mbql/query"- :stages [{:lib/type "mbql.stage/native"- :native "SELECT * FROM venues {{snippet: Remote Snippet}}"- :template-tags {"snippet: Remote Snippet"- {:type "snippet"- :name "snippet: Remote Snippet"- :id "7f2c2a0e-6c1e-4b53-9d0a-0d5a3a1d1c11"- :display-name "Snippet: Remote Snippet"- :snippet-name "Remote Snippet"- :snippet-id snippet-eid}}}]})- tree (merge (shop-tree (assoc resources path (yaml/generate-string native)))- {"snippets/remote_snippet.yaml"- (test-helpers/generate-snippet-yaml snippet-eid "Remote Snippet" "WHERE 1 = 1")})- src (test-helpers/versioned-source :trees {"v0" tree} :current "v0")- result (import-at! src "v0" :force? true)]- (is (= :success (:status result)) (:message result))- (is (t2/exists? :model/NativeQuerySnippet :entity_id snippet-eid))- (is (=? {:query_type :native} (t2/select-one :model/Card :entity_id question-eid)))- (testing "a snippet that nothing defines is still refused"- (let [src (test-helpers/versioned-source- :trees {"v0" (shop-tree (assoc resources path- (yaml/generate-string- (assoc-in native [:dataset_query :stages 0 :template-tags- "snippet: Remote Snippet" :snippet-id]- "nowhereSnippetEid0000"))))}- :current "v0")]- (is (= :error (:status (import-at! src "v0" :force? true)))))))))))+(deftest pull-refuses-native-question-in-apps-collection-test+ (testing "a question in an app's collection is built with the query builder, so a pull refuses one in SQL"+ (with-data-apps-sync+ (let [resources (question-resources)+ path (some #(when (str/includes? % question-eid) %) (keys resources))+ parsed (yaml/parse-string (get resources path))+ native (assoc parsed :dataset_query {:database (:database (:dataset_query parsed))+ :lib/type "mbql/query"+ :stages [{:lib/type "mbql.stage/native"+ :native "SELECT * FROM venues"}]})+ src (test-helpers/versioned-source+ :trees {"v0" (shop-tree (assoc resources path (yaml/generate-string native)))}+ :current "v0")+ result (import-at! src "v0" :force? true)]+ (is (= :error (:status result)))+ (is (str/includes? (:message result) "must be built with the query builder"))+ (is (not (t2/exists? :model/Card :entity_id question-eid)))))))(deftest pull-loads-a-resource-on-a-database-not-connected-yet-test(testing "a resource whose database isn't connected yet loads as a card's does, against a stub database and an@@ -745,7 +574,7 @@(let [mock (test-helpers/create-mock-source :initial-files {"main" (shop-tree (question-resources))})](is (= :success (:status (import-at! mock "main" :force? true))))(let [before (resource-files mock)]- (is (thrown-with-msg? clojure.lang.ExceptionInfo #"cannot move a data app's collection to the trash"+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"stays a top-level collection of data apps"(t2/update! :model/Collection (shop-collection-id) {:archived true})))(is (= :success (:status (export! mock))))(is (= before (resource-files mock)))@@ -770,7 +599,7 @@(testing "an author deletes an app by deleting its directory and its collection's files under collections/data_apps/"(with-data-apps-sync(let [resources (data-apps.tu/build-resources shop-collection-name shop-collection-eid- [{:entity_id question-eid :name "VenuesList" :query (venues-query)}]+ [{:entity_id question-eid :name "VenuesList" :query (venues-stages)}][])src (test-helpers/versioned-source :trees {"v0" (shop-tree resources) "v1" {"README.md" "x"}}:current "v0")]@@ -788,7 +617,7 @@the app, and with it its collection and what it held"(with-data-apps-sync(let [resources (data-apps.tu/build-resources shop-collection-name shop-collection-eid- [{:entity_id question-eid :name "VenuesList" :query (venues-query)}]+ [{:entity_id question-eid :name "VenuesList" :query (venues-stages)}][])v0 (shop-tree resources)v1 (dissoc v0 "data_apps/shop/data_app.yaml" "data_apps/shop/index.js")@@ -810,35 +639,58 @@(mt/user-http-request :crowberto :get 200 (str "card/" card-id))(mt/user-http-request :crowberto :put 200 (str "card/" card-id) {:description "edited in the root"}))))))-(deftest a-card-in-an-apps-collection-reads-only-the-apps-cards-test- (testing "a card there can't read a card outside the app's collection: the export would write a file every pull refuses"+(deftest card-in-apps-collection-reads-only-library-test+ (testing "a card there is a query builder question on tables published to the Library, aggregating only Library+ metrics, and based on no other card, whether it is saved or changed"(with-data-apps-sync- (let [src (test-helpers/versioned-source :trees {"v0" (shop-tree (question-resources))} :current "v0")- mp (mt/metadata-provider)]- (is (= :success (:status (import-at! src "v0" :force? true))))- (mt/with-temp [:model/Card {other-id :id} {:name "Elsewhere"- :dataset_query (lib/query mp (lib.metadata/table mp (mt/id :venues)))}- :model/Card {own-id :id} {:name "Own"- :collection_id (shop-collection-id)- :dataset_query (lib/query mp (lib.metadata/table mp (mt/id :venues)))}]- (let [card-id (t2/select-one-pk :model/Card :entity_id question-eid)- collection-id (shop-collection-id)- reading (fn [id] (lib/query mp (lib.metadata/card mp id)))- save! (fn [query]- (mt/with-temp [:model/Card _ {:name "Saved" :collection_id collection-id :dataset_query query}]))]- (is (thrown-with-msg? clojure.lang.ExceptionInfo #"can read only the app's own cards"- (save! (reading other-id))))- (let [query-before (t2/select-one-fn :dataset_query :model/Card :id card-id)]- (is (thrown-with-msg? clojure.lang.ExceptionInfo #"can read only the app's own cards"- (t2/update! :model/Card card-id {:dataset_query (reading other-id)})))- (is (= query-before (t2/select-one-fn :dataset_query :model/Card :id card-id))))- (testing "one of the app's own cards is fine"- (save! (reading own-id))- (t2/update! :model/Card card-id {:dataset_query (reading own-id)}))- (testing "as is a card elsewhere reading the card outside"- (mt/user-http-request :crowberto :post 200 "card"- {:name "Saved" :type "question" :display "table" :visualization_settings {}- :dataset_query (lib/->legacy-MBQL (reading other-id))}))))))))+ (data-apps.tu/do-with-sources!+ (fn [{library-metric-id :metric-id}]+ (let [src (test-helpers/versioned-source :trees {"v0" (shop-tree (question-resources))} :current "v0")+ mp (mt/metadata-provider)]+ (is (= :success (:status (import-at! src "v0" :force? true))))+ (mt/with-temp [:model/Card {other-metric-id :id} {:name "Venue count elsewhere"+ :type :metric+ :dataset_query (-> (lib/query mp (lib.metadata/table mp (mt/id :venues)))+ (lib/aggregate (lib/count)))}]+ (let [card-id (t2/select-one-pk :model/Card :entity_id question-eid)+ collection-id (shop-collection-id)+ mp (mt/metadata-provider)+ venues (lib/query mp (lib.metadata/table mp (mt/id :venues)))+ save! (fn [query]+ (mt/with-temp [:model/Card _ {:name "Saved" :collection_id collection-id :dataset_query query}]))+ refused? (fn [message query]+ (let [query-before (t2/select-one-fn :dataset_query :model/Card :id card-id)]+ (and (is (thrown-with-msg? clojure.lang.ExceptionInfo message (save! query)))+ (is (thrown-with-msg? clojure.lang.ExceptionInfo message+ (t2/update! :model/Card card-id {:dataset_query query})))+ (is (= query-before (t2/select-one-fn :dataset_query :model/Card :id card-id))))))]+ (testing "a table published to the Library, and a Library metric, are fine"+ (save! venues)+ (save! (lib/aggregate venues (lib.metadata/metric mp library-metric-id)))+ (t2/update! :model/Card card-id {:dataset_query (lib/aggregate venues (lib/count))}))+ (testing "a table that isn't published is refused"+ (refused? #"can read only tables published to the Library, not USERS"+ (lib/query mp (lib.metadata/table mp (mt/id :users)))))+ (testing "so is one joined explicitly"+ (refused? #"can read only tables published to the Library, not CATEGORIES"+ (lib/join venues (lib.metadata/table mp (mt/id :categories)))))+ (testing "or through a foreign key"+ (refused? #"can read only tables published to the Library, not CATEGORIES"+ (lib/breakout venues (some #(when (= (mt/id :categories :name) (:id %)) %)+ (lib/breakoutable-columns venues)))))+ (testing "as is SQL"+ (refused? #"must be built with the query builder"+ (lib/native-query mp "SELECT * FROM venues")))+ (testing "a card as the source, even the app's own"+ (refused? #"not the card"+ (lib/query mp (lib.metadata/card mp card-id))))+ (testing "and a metric outside the Library"+ (refused? #"can use only metrics from the Library"+ (lib/aggregate venues (lib.metadata/metric mp other-metric-id))))+ (testing "a card elsewhere can still read the app's card"+ (mt/user-http-request :crowberto :post 200 "card"+ {:name "Saved" :type "question" :display "table" :visualization_settings {}+ :dataset_query (lib/->legacy-MBQL (lib/query mp (lib.metadata/card mp card-id)))}))))))))))(deftest a-card-in-an-apps-collection-cant-take-embedding-settings-test(testing "embedding parameters would make the export write a file every pull refuses, with embedding itself left off"@@ -847,7 +699,7 @@(is (= :success (:status (import-at! mock "main" :force? true))))(let [card-id (t2/select-one-pk :model/Card :entity_id question-eid)](mt/with-temporary-setting-values [enable-embedding-modular true]- (is (thrown-with-msg? clojure.lang.ExceptionInfo #"must be a question or metric that is not archived"+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"must be a question or metric"(t2/update! :model/Card card-id {:embedding_params {}})))(testing "a card elsewhere takes them"(mt/with-temp [:model/Card {other-id :id} {:name "Elsewhere"}]@@ -862,7 +714,7 @@(is (= :success (:status (import-at! mock "main" :force? true))))(let [collection-id (shop-collection-id)before (resource-files mock)]- (is (thrown-with-msg? clojure.lang.ExceptionInfo #"cannot move a data app's collection to the trash or make it official"+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"stays a top-level collection of data apps"(t2/update! :model/Collection collection-id {:authority_level "official"})))(mt/with-temp [:model/Collection other {:name "Other root" :namespace :data-apps}](is (thrown-with-msg? clojure.lang.ExceptionInfo #"You cannot move a data app's collection"@@ -880,7 +732,7 @@(data-apps.tu/do-with-sources!(fn [{:keys [action-id]}](let [resources (data-apps.tu/build-resources shop-collection-name shop-collection-eid- [{:entity_id question-eid :name "VenuesList" :query (venues-query)}]+ [{:entity_id question-eid :name "VenuesList" :query (venues-stages)}][action-id])mock (test-helpers/create-mock-source :initial-files {"main" (shop-tree resources)})](is (= :success (:status (import-at! mock "main" :force? true))))@@ -918,7 +770,7 @@(data-apps.tu/do-with-sources!(fn [{:keys [action-id]}](let [resources (data-apps.tu/build-resources shop-collection-name shop-collection-eid- [{:entity_id question-eid :name "VenuesList" :query (venues-query)}]+ [{:entity_id question-eid :name "VenuesList" :query (venues-stages)}][action-id])mock (test-helpers/create-mock-source :initial-files {"main" (shop-tree resources)})](is (= :success (:status (import-at! mock "main" :force? true))))@@ -955,20 +807,19 @@(is (= :success (:status (export! mock))))(is (= :success (:status (import-at! mock "main" :force? true)))))))))))-(deftest a-refused-pull-names-the-file-whatever-its-name-test- (testing "a validator failure is reported as what it is when a path has \"branch\" in it, not as a branch error"+(deftest pull-loads-app-whose-collection-is-remote-synced-test+ (testing "an app's collection may be remote-synced, as remote sync marks it once it syncs the collection, so a pull+ that says so loads the app, and the next pull too"(with-data-apps-sync- (let [collection-eid (data-apps.tu/collection-entity-id "branch-ops")- resources (data-apps.tu/build-resources "Data App: branch-ops" collection-eid- [{:entity_id question-eid :name "VenuesList" :query (venues-query)}]- [])- card-file (some #(when (str/includes? % question-eid) %) (keys resources))- tree (data-apps.tu/app-files "branch-ops"- {:name "Branch Ops" :path "index.js" :bundle "B" :collection collection-eid- :resources (update resources card-file- #(yaml/generate-string (assoc (yaml/parse-string %) :type "model")))})- src (test-helpers/versioned-source :trees {"v0" tree} :current "v0")- result (import-at! src "v0" :force? true)]- (is (= :error (:status result)))- (is (str/includes? (:message result) "must be a question or metric"))- (is (str/includes? (:message result) card-file))))))+ (let [tree (shop-tree (question-resources))+ coll-file (data-apps.tu/collection-path shop-collection-name)+ synced (update tree coll-file #(yaml/generate-string (assoc (yaml/parse-string %) :is_remote_synced true)))+ src (test-helpers/versioned-source :trees {"v0" synced "v1" (assoc synced "README.md" "x")} :current "v0")]+ (is (contains? tree coll-file) "the fixture writes the collection's file where the test changes it")+ (let [result (import-at! src "v0" :force? true)]+ (is (= :success (:status result)) (:message result)))+ (is (= (shop-collection-id) (t2/select-one-pk :model/Collection :entity_id shop-collection-eid)))+ (is (true? (t2/select-one-fn :is_remote_synced :model/Collection :entity_id shop-collection-eid)))+ (is (t2/exists? :model/Card :entity_id question-eid :collection_id (shop-collection-id)))+ (let [result (import-at! src "v1" :force? true)]+ (is (= :success (:status result)) (:message result)))))))diff --git a/enterprise/backend/test/metabase_enterprise/transform_testing/api_e2e_test.clj b/enterprise/backend/test/metabase_enterprise/transform_testing/api_e2e_test.cljindex 3faa7c3edf0..dd28cf1ac08 100644--- a/enterprise/backend/test/metabase_enterprise/transform_testing/api_e2e_test.clj+++ b/enterprise/backend/test/metabase_enterprise/transform_testing/api_e2e_test.clj@@ -72,7 +72,7 @@:name "End to end"}created)))(testing "GET returns what POST created"- (is (= created (mt/user-http-request :crowberto :get 200 path))))+ (is (= (assoc created :last_run nil) (mt/user-http-request :crowberto :get 200 path))))(testing "running a passing test"(let [result (mt/user-http-request :crowberto :post 200 (str path "/run"))](is (= #{:status :expectations :tables} (set (keys result))))diff --git a/enterprise/backend/test/metabase_enterprise/transform_testing/api_test.clj b/enterprise/backend/test/metabase_enterprise/transform_testing/api_test.cljindex b9931cfe81d..b1e09c81261 100644--- a/enterprise/backend/test/metabase_enterprise/transform_testing/api_test.clj+++ b/enterprise/backend/test/metabase_enterprise/transform_testing/api_test.clj@@ -41,7 +41,8 @@[:get 402 path][:put 402 path {:name "t"}][:delete 402 path]- [:post 402 (str path "/run")]]]+ [:post 402 (str path "/run")]+ [:get 402 (str path "/run")]]](mt/assert-has-premium-feature-error"Transforms Testing"(apply mt/user-http-request :crowberto request)))))))))@@ -69,7 +70,7 @@:expectations expectations}created)))(testing "GET returns the test"- (is (= created (mt/user-http-request :crowberto :get 200 path))))+ (is (= (assoc created :last_run nil) (mt/user-http-request :crowberto :get 200 path))))(testing "GET / filters by transform"(is (= [(:id created)](map :id (mt/user-http-request :crowberto :get 200 "ee/transform-test" :transform-id transform-id))))@@ -189,3 +190,65 @@(mt/user-http-request :lucky :delete 403 path)(mt/user-http-request :lucky :post 403 (str path "/run"))))(is (t2/exists? :model/TransformTest test-id))))))++(deftest list-runs-test+ (with-transforms-enabled+ (mt/with-temp [:model/Transform {transform-id :id} {}+ :model/TransformTest {test-id :id} {:transform_id transform-id}+ :model/TransformTest {other-id :id} {:transform_id transform-id}+ :model/TransformTestRun {old-id :id} {:transform_test_id test-id+ :status :passed+ :start_time #t "2026-01-01T10:00:00Z"+ :end_time #t "2026-01-01T10:00:02Z"}+ :model/TransformTestRun {failed-id :id} {:transform_test_id test-id+ :initiated_by (mt/user->id :crowberto)+ :status :failed+ :start_time #t "2026-02-01T10:00:00Z"+ :end_time #t "2026-02-01T10:00:02Z"}+ :model/TransformTestRun {new-id :id} {:transform_test_id test-id+ :status :passed+ :start_time #t "2026-03-01T10:00:00Z"+ :end_time #t "2026-03-01T10:00:02Z"}+ :model/TransformTestRun _ {:transform_test_id other-id+ :status :error+ :start_time #t "2026-04-01T10:00:00Z"}]+ (let [path (str "ee/transform-test/" test-id "/run")]+ (testing "lists the runs of the test, newest first, with who started them"+ (is (=? {:data [{:id new-id :status "passed" :initiated_by_user nil}+ {:id failed-id :status "failed" :initiated_by_user {:common_name "Crowberto Corv"}}+ {:id old-id :status "passed"}]+ :total 3+ :offset 0}+ (mt/user-http-request :crowberto :get 200 path))))+ (testing "pages"+ (is (=? {:data [{:id failed-id}] :total 3 :limit 1 :offset 1}+ (mt/user-http-request :crowberto :get 200 path :limit 1 :offset 1))))+ (testing "filters by status"+ (is (=? {:data [{:id failed-id}] :total 1}+ (mt/user-http-request :crowberto :get 200 path :statuses "failed"))))+ (testing "filters by start and end time"+ (is (=? {:data [{:id failed-id}] :total 1}+ (mt/user-http-request :crowberto :get 200 path :start-time "2026-02-01~2026-02-28")))+ (is (=? {:data [{:id new-id}] :total 1}+ (mt/user-http-request :crowberto :get 200 path :end-time "2026-03-01"))))+ (testing "refuses users who can't read the test"+ (mt/user-http-request :rasta :get 403 path))))))++(deftest last-run-test+ (with-transforms-enabled+ (mt/with-temp [:model/Transform {transform-id :id} {}+ :model/TransformTest {test-id :id} {:transform_id transform-id :name "a"}+ :model/TransformTest {never-id :id} {:transform_id transform-id :name "b"}+ :model/TransformTestRun _ {:transform_test_id test-id+ :status :passed+ :start_time #t "2026-01-01T10:00:00Z"}+ :model/TransformTestRun {new-id :id} {:transform_test_id test-id+ :status :failed+ :start_time #t "2026-02-01T10:00:00Z"}]+ (testing "the list carries each test's newest run"+ (is (=? [{:id test-id :last_run {:id new-id :status "failed"}}+ {:id never-id :last_run nil}]+ (mt/user-http-request :crowberto :get 200 "ee/transform-test" :transform-id transform-id))))+ (testing "a single test carries its newest run"+ (is (=? {:id test-id :last_run {:id new-id}}+ (mt/user-http-request :crowberto :get 200 (str "ee/transform-test/" test-id))))))))diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev-entry.tsx b/enterprise/frontend/src/embedding-sdk-package/data-app-dev-entry.tsxindex 0802f5da416..02bc1b259be 100644--- a/enterprise/frontend/src/embedding-sdk-package/data-app-dev-entry.tsx+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev-entry.tsx@@ -26,10 +26,10 @@ import {sdkVersion,} from "virtual:metabase-data-app-dev-config";-import { DATA_APP_PROVIDER_PROP_KEYS } from "metabase-enterprise/data_apps/sandbox/types";+import { DATA_APP_PROVIDER_PROP_KEYS } from "metabase-enterprise/data-apps/sandbox/types";// The same baseline reset the production iframe loads (`iframe-vendors.ts`), so the// dev preview matches production. style-loader injects it at runtime.-import "metabase-enterprise/data_apps/sandbox/iframe-baseline.css";+import "metabase-enterprise/data-apps/sandbox/iframe-baseline.css";const authConfig = {metabaseInstanceUrl: import.meta.env.DATA_APP_MB_URL ?? "",diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-dev.tsindex a2385574842..5953643649c 100644--- a/enterprise/frontend/src/embedding-sdk-package/data-app-dev.ts+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev.ts@@ -14,4 +14,4 @@ export type {DataAppDiagnosticPayload,DataAppDiagnosticsReport,} from "./data-app-dev/types/diagnostics-channel";-export { createDataAppSandbox } from "metabase-enterprise/data_apps/sandbox/sandbox";+export { createDataAppSandbox } from "metabase-enterprise/data-apps/sandbox/sandbox";diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DevToolbar/diagnostics.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DevToolbar/diagnostics.tsindex de593f9010e..98f109546cf 100644--- a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DevToolbar/diagnostics.ts+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DevToolbar/diagnostics.ts@@ -1,4 +1,4 @@-import type { SandboxBlockedEvent } from "metabase-enterprise/data_apps/sandbox/types";+import type { SandboxBlockedEvent } from "metabase-enterprise/data-apps/sandbox/types";import {trimDiagnosticEntries,diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/constants/bundle.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/constants/bundle.tsindex 2406596247b..a0dd6ee9090 100644--- a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/constants/bundle.ts+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/constants/bundle.ts@@ -3,7 +3,7 @@ export {DATA_APP_FACTORY_GLOBAL,DATA_APP_GLOBALS,DATA_APP_GLOBAL_NAMES,-} from "metabase-enterprise/data_apps/sandbox/globals";+} from "metabase-enterprise/data-apps/sandbox/globals";export const DATA_APP_ENTRY = "src/index.tsx";diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app.ts b/enterprise/frontend/src/embedding-sdk-package/data-app.tsindex cc4ed2c4c2d..a1fd9b46847 100644--- a/enterprise/frontend/src/embedding-sdk-package/data-app.ts+++ b/enterprise/frontend/src/embedding-sdk-package/data-app.ts@@ -73,4 +73,4 @@ export type {export type {DataAppFactory,DataAppMetabaseProviderProps,-} from "metabase-enterprise/data_apps/sandbox/types";+} from "metabase-enterprise/data-apps/sandbox/types";diff --git a/enterprise/frontend/src/metabase-enterprise/api/index.ts b/enterprise/frontend/src/metabase-enterprise/api/index.tsindex 7330db355ef..a18355b8268 100644--- a/enterprise/frontend/src/metabase-enterprise/api/index.ts+++ b/enterprise/frontend/src/metabase-enterprise/api/index.ts@@ -27,4 +27,5 @@ export * from "./support-access-grants";export * from "./table";export * from "./tags";export * from "./tenants";+export * from "./transform-test";export * from "./upload-management";diff --git a/enterprise/frontend/src/metabase-enterprise/api/tags.ts b/enterprise/frontend/src/metabase-enterprise/api/tags.tsindex 536f2470a26..7cdf5d79b29 100644--- a/enterprise/frontend/src/metabase-enterprise/api/tags.ts+++ b/enterprise/frontend/src/metabase-enterprise/api/tags.ts@@ -27,6 +27,8 @@ import {type SupportAccessGrant,type TableDependencyNode,type TransformDependencyNode,+ type TransformTest,+ type TransformTestRun,} from "metabase-types/api";export const ENTERPRISE_TAG_TYPES = [@@ -55,6 +57,8 @@ export const ENTERPRISE_TAG_TYPES = ["data-complexity-scores","security-advisory","session",+ "transform-test",+ "transform-test-run",] as const;export type EnterpriseTagType = TagType | (typeof ENTERPRISE_TAG_TYPES)[number];@@ -287,3 +291,33 @@ export function provideSourceReplacementRunListTags(...runs.flatMap(provideSourceReplacementRunTags),];}++export function provideTransformTestTags(+ test: TransformTest,+): TagDescription<EnterpriseTagType>[] {+ return [idTag("transform-test", test.id)];+}++export function provideTransformTestListTags(+ tests: TransformTest[],+): TagDescription<EnterpriseTagType>[] {+ return [+ listTag("transform-test"),+ ...tests.flatMap(provideTransformTestTags),+ ];+}++export function provideTransformTestRunTags(+ run: TransformTestRun,+): TagDescription<EnterpriseTagType>[] {+ return [idTag("transform-test-run", run.id)];+}++export function provideTransformTestRunListTags(+ runs: TransformTestRun[],+): TagDescription<EnterpriseTagType>[] {+ return [+ listTag("transform-test-run"),+ ...runs.flatMap(provideTransformTestRunTags),+ ];+}diff --git a/enterprise/frontend/src/metabase-enterprise/api/transform-test.ts b/enterprise/frontend/src/metabase-enterprise/api/transform-test.tsnew file mode 100644index 00000000000..824467e62a6--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/api/transform-test.ts@@ -0,0 +1,75 @@+import type {+ ListTransformTestRunsRequest,+ ListTransformTestRunsResponse,+ ListTransformTestsRequest,+ RunTransformTestResponse,+ TransformTest,+ TransformTestId,+} from "metabase-types/api";++import { EnterpriseApi } from "./api";+import {+ idTag,+ invalidateTags,+ listTag,+ provideTransformTestListTags,+ provideTransformTestRunListTags,+ provideTransformTestTags,+} from "./tags";++export const transformTestApi = EnterpriseApi.injectEndpoints({+ endpoints: (builder) => ({+ listTransformTests: builder.query<+ TransformTest[],+ ListTransformTestsRequest+ >({+ query: (params) => ({+ method: "GET",+ url: "/api/ee/transform-test",+ params,+ }),+ providesTags: (tests = []) => provideTransformTestListTags(tests),+ }),+ getTransformTest: builder.query<TransformTest, TransformTestId>({+ query: (id) => ({+ method: "GET",+ url: `/api/ee/transform-test/${id}`,+ }),+ providesTags: (test) => (test ? provideTransformTestTags(test) : []),+ }),+ listTransformTestRuns: builder.query<+ ListTransformTestRunsResponse,+ ListTransformTestRunsRequest+ >({+ query: ({ id, ...params }) => ({+ method: "GET",+ url: `/api/ee/transform-test/${id}/run`,+ params,+ }),+ providesTags: (response) =>+ provideTransformTestRunListTags(response?.data ?? []),+ }),+ runTransformTest: builder.mutation<+ RunTransformTestResponse,+ TransformTestId+ >({+ query: (id) => ({+ method: "POST",+ url: `/api/ee/transform-test/${id}/run`,+ }),+ invalidatesTags: (_, error, id) =>+ invalidateTags(error, [+ listTag("transform-test"),+ idTag("transform-test", id),+ listTag("transform-test-run"),+ ]),+ }),+ }),+});++export const {+ useListTransformTestsQuery,+ useGetTransformTestQuery,+ useListTransformTestRunsQuery,+ useRunTransformTestMutation,+} = transformTestApi;diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/constants.ts b/enterprise/frontend/src/metabase-enterprise/data-apps/constants.tssimilarity index 100%rename from enterprise/frontend/src/metabase-enterprise/data_apps/constants.tsrename to enterprise/frontend/src/metabase-enterprise/data-apps/constants.tsdiff --git a/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/components/DataAppActionHeader/DataAppActionHeader.tsx b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/components/DataAppActionHeader/DataAppActionHeader.tsxnew file mode 100644index 00000000000..a5138da0a92--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/components/DataAppActionHeader/DataAppActionHeader.tsx@@ -0,0 +1,54 @@+import { t } from "ttag";++import type { PillTab } from "metabase/common/components/PillTabNavigation";+import { PLUGIN_DEPENDENCIES } from "metabase/plugins";+import type { StackProps } from "metabase/ui";+import * as Urls from "metabase/urls";+import type { DataApp, WritebackQueryAction } from "metabase-types/api";++import { DataAppItemHeader } from "../DataAppItemHeader";++type DataAppActionHeaderProps = {+ app: DataApp;+ action: WritebackQueryAction;+} & Omit<StackProps, "title">;++export function DataAppActionHeader({+ app,+ action,+ ...stackProps+}: DataAppActionHeaderProps) {+ const fieldsUrl = Urls.dataStudioDataAppActionFields(app.name, action.id);+ const tabs: PillTab[] = [+ {+ label: t`Definition`,+ to: Urls.dataStudioDataAppAction(app.name, action.id),+ },+ {+ label: t`Fields`,+ to: fieldsUrl,+ isSelected: (pathname: string) => pathname.startsWith(fieldsUrl),+ },+ ...(PLUGIN_DEPENDENCIES.isEnabled+ ? [+ {+ label: t`Dependencies`,+ to: Urls.dataStudioDataAppActionDependencies(app.name, action.id),+ },+ ]+ : []),+ ];++ return (+ <DataAppItemHeader+ app={app}+ name={action.name}+ icon="bolt"+ sectionName={t`Actions`}+ sectionUrl={Urls.dataStudioDataAppActions(app.name)}+ tabs={tabs}+ data-testid="data-app-action-header"+ {...stackProps}+ />+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/components/DataAppActionHeader/index.ts b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/components/DataAppActionHeader/index.tsnew file mode 100644index 00000000000..fe9cfc61d82--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/components/DataAppActionHeader/index.ts@@ -0,0 +1 @@+export { DataAppActionHeader } from "./DataAppActionHeader";diff --git a/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/components/DataAppHeader/DataAppHeader.tsx b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/components/DataAppHeader/DataAppHeader.tsxnew file mode 100644index 00000000000..12996432654--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/components/DataAppHeader/DataAppHeader.tsx@@ -0,0 +1,49 @@+import { t } from "ttag";++import { Link } from "metabase/common/components/Link";+import { PillTabNavigation } from "metabase/common/components/PillTabNavigation";+import { DataStudioBreadcrumbs } from "metabase/common/data-studio/components/DataStudioBreadcrumbs";+import {+ PaneHeader,+ PanelHeaderTitle,+} from "metabase/common/data-studio/components/PaneHeader";+import * as Urls from "metabase/urls";+import type { DataApp } from "metabase-types/api";++import { DataAppMoreMenu } from "../DataAppMoreMenu";++type DataAppHeaderProps = {+ app: DataApp;+};++export function DataAppHeader({ app }: DataAppHeaderProps) {+ return (+ <PaneHeader+ title={<PanelHeaderTitle>{app.display_name}</PanelHeaderTitle>}+ menu={<DataAppMoreMenu app={app} />}+ tabs={+ <PillTabNavigation+ tabs={[+ { label: t`Overview`, to: Urls.dataStudioDataApp(app.name) },+ {+ label: t`Questions`,+ to: Urls.dataStudioDataAppQuestions(app.name),+ },+ { label: t`Actions`, to: Urls.dataStudioDataAppActions(app.name) },+ {+ label: t`Permissions`,+ to: Urls.dataStudioDataAppPermissions(app.name),+ },+ ]}+ />+ }+ breadcrumbs={+ <DataStudioBreadcrumbs>+ <Link to={Urls.dataStudioDataApps()}>{t`Data apps`}</Link>+ {app.display_name}+ </DataStudioBreadcrumbs>+ }+ data-testid="data-app-header"+ />+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/components/DataAppHeader/index.ts b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/components/DataAppHeader/index.tsnew file mode 100644index 00000000000..87ffef23f14--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/components/DataAppHeader/index.ts@@ -0,0 +1 @@+export { DataAppHeader } from "./DataAppHeader";diff --git a/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/components/DataAppItemHeader/DataAppItemHeader.tsx b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/components/DataAppItemHeader/DataAppItemHeader.tsxnew file mode 100644index 00000000000..f23a91f3fb9--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/components/DataAppItemHeader/DataAppItemHeader.tsx@@ -0,0 +1,51 @@+import { t } from "ttag";++import { Link } from "metabase/common/components/Link";+import {+ type PillTab,+ PillTabNavigation,+} from "metabase/common/components/PillTabNavigation";+import { DataStudioBreadcrumbs } from "metabase/common/data-studio/components/DataStudioBreadcrumbs";+import {+ PaneHeader,+ PanelHeaderTitle,+} from "metabase/common/data-studio/components/PaneHeader";+import type { StackProps } from "metabase/ui";+import * as Urls from "metabase/urls";+import type { DataApp, IconName } from "metabase-types/api";++type DataAppItemHeaderProps = {+ app: DataApp;+ name: string;+ icon: IconName;+ sectionName: string;+ sectionUrl: string;+ tabs: PillTab[];+} & Omit<StackProps, "title">;++export function DataAppItemHeader({+ app,+ name,+ icon,+ sectionName,+ sectionUrl,+ tabs,+ ...stackProps+}: DataAppItemHeaderProps) {+ return (+ <PaneHeader+ title={<PanelHeaderTitle>{name}</PanelHeaderTitle>}+ icon={icon}+ tabs={<PillTabNavigation tabs={tabs} />}+ breadcrumbs={+ <DataStudioBreadcrumbs>+ <Link to={Urls.dataStudioDataApps()}>{t`Data apps`}</Link>+ <Link to={Urls.dataStudioDataApp(app.name)}>{app.display_name}</Link>+ <Link to={sectionUrl}>{sectionName}</Link>+ {name}+ </DataStudioBreadcrumbs>+ }+ {...stackProps}+ />+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/components/DataAppItemHeader/index.ts b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/components/DataAppItemHeader/index.tsnew file mode 100644index 00000000000..7fc3dd01e12--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/components/DataAppItemHeader/index.ts@@ -0,0 +1 @@+export { DataAppItemHeader } from "./DataAppItemHeader";diff --git a/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/components/DataAppItemList/DataAppItemList.tsx b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/components/DataAppItemList/DataAppItemList.tsxnew file mode 100644index 00000000000..c604b85d76b--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/components/DataAppItemList/DataAppItemList.tsx@@ -0,0 +1,104 @@+import { useCallback, useMemo, useState } from "react";+import { t } from "ttag";++import { useListCollectionItemsQuery } from "metabase/api";+import { ListEmptyState } from "metabase/common/components/ListEmptyState";+import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";+import { useNavigate } from "metabase/router";+import {+ Card,+ Ellipsified,+ Flex,+ Icon,+ Stack,+ TextInput,+ TreeTable,+ type TreeTableColumnDef,+ TreeTableSkeleton,+ useTreeTableInstance,+} from "metabase/ui";+import type { CollectionItem, DataApp } from "metabase-types/api";++type DataAppItemListProps = {+ app: DataApp;+ model: "card" | "action";+ emptyMessage: string;+ getItemUrl: (itemId: number) => string;+};++export function DataAppItemList({+ app,+ model,+ emptyMessage,+ getItemUrl,+}: DataAppItemListProps) {+ const navigate = useNavigate();+ const [searchQuery, setSearchQuery] = useState("");+ const { data, isLoading, error } = useListCollectionItemsQuery({+ id: app.resource_collection_id,+ models: [model],+ });+ const items = useMemo(() => data?.data ?? [], [data]);++ const handleRowActivate = useCallback(+ (row: { original: CollectionItem }) => {+ navigate(getItemUrl(row.original.id));+ },+ [navigate, getItemUrl],+ );++ const columns = useMemo<TreeTableColumnDef<CollectionItem>[]>(+ () => [+ {+ id: "name",+ accessorKey: "name",+ header: t`Name`,+ minWidth: 200,+ cell: ({ row }) => <Ellipsified>{row.original.name}</Ellipsified>,+ },+ ],+ [],+ );++ const treeTableInstance = useTreeTableInstance({+ data: items,+ columns,+ getNodeId: (item) => String(item.id),+ globalFilter: searchQuery,+ onGlobalFilterChange: setSearchQuery,+ onRowActivate: handleRowActivate,+ });++ if (error) {+ return <LoadingAndErrorWrapper loading={false} error={error} />;+ }++ return (+ <Stack style={{ overflow: "hidden" }}>+ <TextInput+ placeholder={t`Search...`}+ leftSection={<Icon name="search" />}+ bdrs="sm"+ value={searchQuery}+ onChange={(event) => setSearchQuery(event.target.value)}+ />+ <Flex direction="column" flex={1} mih={0}>+ <Card withBorder p={0}>+ {isLoading ? (+ <TreeTableSkeleton columnWidths={[1]} />+ ) : (+ <TreeTable+ instance={treeTableInstance}+ emptyState={+ <ListEmptyState+ label={searchQuery ? t`Nothing found` : emptyMessage}+ />+ }+ onRowClick={handleRowActivate}+ />+ )}+ </Card>+ </Flex>+ </Stack>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/components/DataAppItemList/index.ts b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/components/DataAppItemList/index.tsnew file mode 100644index 00000000000..dcf784fd6b3--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/components/DataAppItemList/index.ts@@ -0,0 +1 @@+export { DataAppItemList } from "./DataAppItemList";diff --git a/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/components/DataAppMoreMenu/DataAppMoreMenu.tsx b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/components/DataAppMoreMenu/DataAppMoreMenu.tsxnew file mode 100644index 00000000000..43117f216ae--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/components/DataAppMoreMenu/DataAppMoreMenu.tsx@@ -0,0 +1,87 @@+import type { MouseEvent } from "react";+import { t } from "ttag";++import { MoreMenuButton } from "metabase/common/data-studio/components/MoreMenuButton";+import { useConfirmation, useMetadataToasts } from "metabase/common/hooks";+import { Icon, Menu } from "metabase/ui";+import * as Urls from "metabase/urls";+import { useSetDataAppEnabledMutation } from "metabase-enterprise/api";+import type { DataApp } from "metabase-types/api";++import { isDataAppOpenable } from "../../utils";++type DataAppMoreMenuProps = {+ app: DataApp;+};++export function DataAppMoreMenu({ app }: DataAppMoreMenuProps) {+ const [setDataAppEnabled] = useSetDataAppEnabledMutation();+ const { sendSuccessToast, sendErrorToast } = useMetadataToasts();+ const { show: showConfirmation, modalContent } = useConfirmation();++ const handleToggleEnabled = () => {+ const enabled = !app.enabled;+ showConfirmation({+ title: enabled+ ? t`Make ${app.display_name} live?`+ : t`Make ${app.display_name} a draft?`,+ message: enabled+ ? t`People in its groups will be able to open it at ${Urls.dataApp(app.name)}.`+ : t`Nobody will be able to open it until you make it live again. This doesn’t change the app.`,+ confirmButtonText: enabled ? t`Make live` : t`Make draft`,+ confirmButtonProps: { color: "brand" },+ onConfirm: async () => {+ const { error } = await setDataAppEnabled({ name: app.name, enabled });+ if (error) {+ sendErrorToast(t`Failed to update ${app.display_name}`);+ } else {+ sendSuccessToast(+ enabled+ ? t`${app.display_name} is live`+ : t`${app.display_name} is a draft`,+ );+ }+ },+ });+ };++ const handleTargetClick = (event: MouseEvent) => {+ event.preventDefault();+ event.stopPropagation();+ };++ return (+ <>+ <Menu position="bottom-start">+ <Menu.Target>+ <MoreMenuButton+ aria-label={t`Data app options`}+ onClick={handleTargetClick}+ />+ </Menu.Target>+ <Menu.Dropdown onClick={(event) => event.stopPropagation()}>+ {isDataAppOpenable(app) && (+ <Menu.Item+ component="a"+ href={Urls.getSubpathSafeUrl(Urls.dataApp(app.name))}+ target="_blank"+ rel="noreferrer"+ leftSection={<Icon name="external" />}+ >+ {t`Open app`}+ </Menu.Item>+ )}+ <Menu.Item+ leftSection={+ <Icon name={app.enabled ? "eye_crossed_out" : "eye"} />+ }+ onClick={handleToggleEnabled}+ >+ {app.enabled ? t`Make draft` : t`Make live`}+ </Menu.Item>+ </Menu.Dropdown>+ </Menu>+ {modalContent}+ </>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/components/DataAppMoreMenu/DataAppMoreMenu.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/components/DataAppMoreMenu/DataAppMoreMenu.unit.spec.tsxnew file mode 100644index 00000000000..cc10bb5e654--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/components/DataAppMoreMenu/DataAppMoreMenu.unit.spec.tsx@@ -0,0 +1,80 @@+import userEvent from "@testing-library/user-event";+import fetchMock from "fetch-mock";++import { setupUpdateDataAppEndpoint } from "__support__/server-mocks";+import { renderWithProviders, screen, within } from "__support__/ui";+import type { DataApp } from "metabase-types/api";+import { createMockDataApp } from "metabase-types/api/mocks";++import { DataAppMoreMenu } from "./DataAppMoreMenu";++type SetupOpts = {+ app: DataApp;+};++function setup({ app }: SetupOpts) {+ setupUpdateDataAppEndpoint({ ...app, enabled: !app.enabled });+ renderWithProviders(<DataAppMoreMenu app={app} />, { withRouter: true });+}++const openMenu = () =>+ userEvent.click(screen.getByRole("button", { name: "Data app options" }));++describe("DataAppMoreMenu", () => {+ it("offers to open a live app and make it a draft", async () => {+ setup({ app: createMockDataApp({ name: "sales", enabled: true }) });++ await openMenu();++ expect(+ await screen.findByRole("menuitem", { name: /Open app/ }),+ ).toHaveAttribute("href", "/apps/sales");+ expect(+ screen.getByRole("menuitem", { name: /Make draft/ }),+ ).toBeInTheDocument();+ });++ it("does not offer to open a draft app", async () => {+ setup({ app: createMockDataApp({ enabled: false }) });++ await openMenu();++ expect(+ await screen.findByRole("menuitem", { name: /Make live/ }),+ ).toBeInTheDocument();+ expect(+ screen.queryByRole("menuitem", { name: /Open app/ }),+ ).not.toBeInTheDocument();+ });++ it("makes a live app a draft only after confirmation", async () => {+ setup({+ app: createMockDataApp({+ name: "sales",+ display_name: "Sales",+ enabled: true,+ }),+ });++ await openMenu();+ await userEvent.click(+ await screen.findByRole("menuitem", { name: /Make draft/ }),+ );++ const dialog = await screen.findByRole("dialog");+ expect(within(dialog).getByText("Make Sales a draft?")).toBeInTheDocument();+ expect(fetchMock.callHistory.calls("path:/api/ee/apps/sales")).toHaveLength(+ 0,+ );++ await userEvent.click(+ within(dialog).getByRole("button", { name: "Make draft" }),+ );++ const calls = fetchMock.callHistory.calls("path:/api/ee/apps/sales");+ expect(calls).toHaveLength(1);+ expect(JSON.parse(String(calls[0].options.body))).toEqual({+ enabled: false,+ });+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/components/DataAppMoreMenu/index.ts b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/components/DataAppMoreMenu/index.tsnew file mode 100644index 00000000000..54ef70f160d--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/components/DataAppMoreMenu/index.ts@@ -0,0 +1 @@+export { DataAppMoreMenu } from "./DataAppMoreMenu";diff --git a/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/components/DataAppQuestionHeader/DataAppQuestionHeader.tsx b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/components/DataAppQuestionHeader/DataAppQuestionHeader.tsxnew file mode 100644index 00000000000..a93c799b07c--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/components/DataAppQuestionHeader/DataAppQuestionHeader.tsx@@ -0,0 +1,45 @@+import { t } from "ttag";++import type { PillTab } from "metabase/common/components/PillTabNavigation";+import { PLUGIN_DEPENDENCIES } from "metabase/plugins";+import * as Urls from "metabase/urls";+import type { Card, DataApp } from "metabase-types/api";++import { DataAppItemHeader } from "../DataAppItemHeader";++type DataAppQuestionHeaderProps = {+ app: DataApp;+ card: Card;+};++export function DataAppQuestionHeader({+ app,+ card,+}: DataAppQuestionHeaderProps) {+ const tabs: PillTab[] = [+ {+ label: t`Overview`,+ to: Urls.dataStudioDataAppQuestion(app.name, card.id),+ },+ ...(PLUGIN_DEPENDENCIES.isEnabled+ ? [+ {+ label: t`Dependencies`,+ to: Urls.dataStudioDataAppQuestionDependencies(app.name, card.id),+ },+ ]+ : []),+ ];++ return (+ <DataAppItemHeader+ app={app}+ name={card.name}+ icon="table2"+ sectionName={t`Questions`}+ sectionUrl={Urls.dataStudioDataAppQuestions(app.name)}+ tabs={tabs}+ data-testid="data-app-question-header"+ />+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/components/DataAppQuestionHeader/DataAppQuestionHeader.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/components/DataAppQuestionHeader/DataAppQuestionHeader.unit.spec.tsxnew file mode 100644index 00000000000..d3a658708e7--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/components/DataAppQuestionHeader/DataAppQuestionHeader.unit.spec.tsx@@ -0,0 +1,38 @@+import { renderWithProviders, screen } from "__support__/ui";+import { createMockCard, createMockDataApp } from "metabase-types/api/mocks";++import { DataAppQuestionHeader } from "./DataAppQuestionHeader";++function setup() {+ renderWithProviders(+ <DataAppQuestionHeader+ app={createMockDataApp({+ name: "order-desk",+ display_name: "Order desk",+ })}+ card={createMockCard({ id: 7, name: "Recent orders" })}+ />,+ { withRouter: true },+ );+}++describe("DataAppQuestionHeader", () => {+ it("links the breadcrumbs to the app and its questions", () => {+ setup();++ const breadcrumbs = screen.getByTestId("data-studio-breadcrumbs");+ expect(screen.getByRole("link", { name: "Data apps" })).toHaveAttribute(+ "href",+ "/data-studio/apps",+ );+ expect(screen.getByRole("link", { name: "Order desk" })).toHaveAttribute(+ "href",+ "/data-studio/apps/order-desk",+ );+ expect(screen.getByRole("link", { name: "Questions" })).toHaveAttribute(+ "href",+ "/data-studio/apps/order-desk/questions",+ );+ expect(breadcrumbs).toHaveTextContent("Recent orders");+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/components/DataAppQuestionHeader/index.ts b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/components/DataAppQuestionHeader/index.tsnew file mode 100644index 00000000000..2a4ace210d8--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/components/DataAppQuestionHeader/index.ts@@ -0,0 +1 @@+export { DataAppQuestionHeader } from "./DataAppQuestionHeader";diff --git a/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/hooks/use-route-data-app-action/index.ts b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/hooks/use-route-data-app-action/index.tsnew file mode 100644index 00000000000..eb93d7891e0--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/hooks/use-route-data-app-action/index.ts@@ -0,0 +1 @@+export { useRouteDataAppAction } from "./use-route-data-app-action";diff --git a/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/hooks/use-route-data-app-action/use-route-data-app-action.ts b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/hooks/use-route-data-app-action/use-route-data-app-action.tsnew file mode 100644index 00000000000..acc1c3b0c50--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/hooks/use-route-data-app-action/use-route-data-app-action.ts@@ -0,0 +1,44 @@+import { t } from "ttag";++import { skipToken, useGetActionQuery } from "metabase/api";+import { useActionDatabases } from "metabase/data-studio/actions/hooks/use-action-databases";+import { useParams } from "metabase/router";+import * as Urls from "metabase/urls";+import { useGetDataAppQuery } from "metabase-enterprise/api";++export function useRouteDataAppAction() {+ const params = useParams<{ name: string; actionId: string }>();+ const name = params.name ?? "";+ const actionId = Urls.extractEntityId(params.actionId);+ const {+ data: app,+ isLoading: isLoadingApp,+ error: appError,+ } = useGetDataAppQuery(name);+ const {+ currentData,+ isFetching: isFetchingAction,+ error: actionFetchError,+ } = useGetActionQuery(actionId != null ? { id: actionId } : skipToken);+ const {+ databases,+ isLoading: isLoadingDatabases,+ error: databasesError,+ } = useActionDatabases();++ const action = currentData?.type === "query" ? currentData : undefined;+ const isLoadingAction = currentData === undefined && isFetchingAction;+ const isActionNotFound =+ !isLoadingAction && actionFetchError === undefined && action === undefined;+ const actionError = isActionNotFound+ ? t`Action not found.`+ : actionFetchError;++ return {+ app,+ action,+ databases,+ isLoading: isLoadingApp || isLoadingAction || isLoadingDatabases,+ error: appError ?? actionError ?? databasesError,+ };+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/hooks/use-route-data-app-question/index.ts b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/hooks/use-route-data-app-question/index.tsnew file mode 100644index 00000000000..faeaaf00fb4--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/hooks/use-route-data-app-question/index.ts@@ -0,0 +1 @@+export { useRouteDataAppQuestion } from "./use-route-data-app-question";diff --git a/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/hooks/use-route-data-app-question/use-route-data-app-question.ts b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/hooks/use-route-data-app-question/use-route-data-app-question.tsnew file mode 100644index 00000000000..f190e54f5e9--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/hooks/use-route-data-app-question/use-route-data-app-question.ts@@ -0,0 +1,27 @@+import { skipToken, useGetCardQuery } from "metabase/api";+import { useParams } from "metabase/router";+import * as Urls from "metabase/urls";+import { useGetDataAppQuery } from "metabase-enterprise/api";++export function useRouteDataAppQuestion() {+ const params = useParams<{ name: string; cardId: string }>();+ const name = params.name ?? "";+ const cardId = Urls.extractEntityId(params.cardId);+ const {+ data: app,+ isLoading: isLoadingApp,+ error: appError,+ } = useGetDataAppQuery(name);+ const {+ data: card,+ isLoading: isLoadingCard,+ error: cardError,+ } = useGetCardQuery(cardId != null ? { id: cardId } : skipToken);++ return {+ app,+ card,+ isLoading: isLoadingApp || isLoadingCard,+ error: appError ?? cardError,+ };+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/hooks/use-route-data-app/index.ts b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/hooks/use-route-data-app/index.tsnew file mode 100644index 00000000000..036486d5d38--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/hooks/use-route-data-app/index.ts@@ -0,0 +1 @@+export { useRouteDataApp } from "./use-route-data-app";diff --git a/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/hooks/use-route-data-app/use-route-data-app.ts b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/hooks/use-route-data-app/use-route-data-app.tsnew file mode 100644index 00000000000..09162ec803e--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/hooks/use-route-data-app/use-route-data-app.ts@@ -0,0 +1,8 @@+import { useParams } from "metabase/router";+import { useGetDataAppQuery } from "metabase-enterprise/api";++export function useRouteDataApp() {+ const { name = "" } = useParams<{ name: string }>();+ const { data: app, isLoading, error } = useGetDataAppQuery(name);+ return { app, isLoading, error };+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppActionDefinitionPage/DataAppActionDefinitionPage.tsx b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppActionDefinitionPage/DataAppActionDefinitionPage.tsxnew file mode 100644index 00000000000..2d23f33387f--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppActionDefinitionPage/DataAppActionDefinitionPage.tsx@@ -0,0 +1,26 @@+import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";+import { PageContainer } from "metabase/common/data-studio/components/PageContainer";+import { ActionDefinitionContent } from "metabase/data-studio/actions/components/ActionDefinitionContent";+import { Center } from "metabase/ui";++import { DataAppActionHeader } from "../../components/DataAppActionHeader";+import { useRouteDataAppAction } from "../../hooks/use-route-data-app-action";++export function DataAppActionDefinitionPage() {+ const { app, action, databases, isLoading, error } = useRouteDataAppAction();++ if (isLoading || error != null || app == null || action == null) {+ return (+ <Center h="100%">+ <LoadingAndErrorWrapper loading={isLoading} error={error} />+ </Center>+ );+ }++ return (+ <PageContainer data-testid="data-app-action-definition">+ <DataAppActionHeader app={app} action={action} />+ <ActionDefinitionContent action={action} databases={databases} />+ </PageContainer>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppActionDefinitionPage/index.ts b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppActionDefinitionPage/index.tsnew file mode 100644index 00000000000..944c203e54b--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppActionDefinitionPage/index.ts@@ -0,0 +1 @@+export { DataAppActionDefinitionPage } from "./DataAppActionDefinitionPage";diff --git a/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppActionDependenciesPage/DataAppActionDependenciesPage.tsx b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppActionDependenciesPage/DataAppActionDependenciesPage.tsxnew file mode 100644index 00000000000..9fe40dec6c6--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppActionDependenciesPage/DataAppActionDependenciesPage.tsx@@ -0,0 +1,30 @@+import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";+import { PageContainer } from "metabase/common/data-studio/components/PageContainer";+import { ActionDependenciesContent } from "metabase/data-studio/actions/components/ActionDependenciesContent";+import { Center } from "metabase/ui";+import * as Urls from "metabase/urls";++import { DataAppActionHeader } from "../../components/DataAppActionHeader";+import { useRouteDataAppAction } from "../../hooks/use-route-data-app-action";++export function DataAppActionDependenciesPage() {+ const { app, action, isLoading, error } = useRouteDataAppAction();++ if (isLoading || error != null || app == null || action == null) {+ return (+ <Center h="100%">+ <LoadingAndErrorWrapper loading={isLoading} error={error} />+ </Center>+ );+ }++ return (+ <PageContainer data-testid="data-app-action-dependencies">+ <DataAppActionHeader app={app} action={action} />+ <ActionDependenciesContent+ action={action}+ baseUrl={Urls.dataStudioDataAppActionDependencies(app.name, action.id)}+ />+ </PageContainer>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppActionDependenciesPage/index.ts b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppActionDependenciesPage/index.tsnew file mode 100644index 00000000000..bee1db83044--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppActionDependenciesPage/index.ts@@ -0,0 +1 @@+export { DataAppActionDependenciesPage } from "./DataAppActionDependenciesPage";diff --git a/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppActionFieldsPage/DataAppActionFieldsPage.tsx b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppActionFieldsPage/DataAppActionFieldsPage.tsxnew file mode 100644index 00000000000..58cdcdb4537--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppActionFieldsPage/DataAppActionFieldsPage.tsx@@ -0,0 +1,37 @@+import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";+import { PageContainer } from "metabase/common/data-studio/components/PageContainer";+import { ActionFieldsContent } from "metabase/data-studio/actions/components/ActionFieldsContent";+import { canEditActionQuery } from "metabase/data-studio/actions/utils";+import { useParams } from "metabase/router";+import { Center } from "metabase/ui";+import * as Urls from "metabase/urls";++import { DataAppActionHeader } from "../../components/DataAppActionHeader";+import { useRouteDataAppAction } from "../../hooks/use-route-data-app-action";++export function DataAppActionFieldsPage() {+ const { fieldId } = useParams<{ fieldId?: string }>();+ const { app, action, databases, isLoading, error } = useRouteDataAppAction();++ if (isLoading || error != null || app == null || action == null) {+ return (+ <Center h="100%">+ <LoadingAndErrorWrapper loading={isLoading} error={error} />+ </Center>+ );+ }++ return (+ <PageContainer data-testid="data-app-action-fields" gap="lg" px={0} pb={0}>+ <DataAppActionHeader app={app} action={action} px="3.5rem" />+ <ActionFieldsContent+ action={action}+ fieldId={fieldId}+ canChangeFieldType={canEditActionQuery(action, databases)}+ getFieldsUrl={(fieldId) =>+ Urls.dataStudioDataAppActionFields(app.name, action.id, fieldId)+ }+ />+ </PageContainer>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppActionFieldsPage/index.ts b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppActionFieldsPage/index.tsnew file mode 100644index 00000000000..75a61dc59d3--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppActionFieldsPage/index.ts@@ -0,0 +1 @@+export { DataAppActionFieldsPage } from "./DataAppActionFieldsPage";diff --git a/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppActionsPage/DataAppActionsPage.tsx b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppActionsPage/DataAppActionsPage.tsxnew file mode 100644index 00000000000..36884953cef--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppActionsPage/DataAppActionsPage.tsx@@ -0,0 +1,36 @@+import { t } from "ttag";++import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";+import { PageContainer } from "metabase/common/data-studio/components/PageContainer";+import { Center } from "metabase/ui";+import * as Urls from "metabase/urls";++import { DataAppHeader } from "../../components/DataAppHeader";+import { DataAppItemList } from "../../components/DataAppItemList";+import { useRouteDataApp } from "../../hooks/use-route-data-app";++export function DataAppActionsPage() {+ const { app, isLoading, error } = useRouteDataApp();++ if (isLoading || error != null || app == null) {+ return (+ <Center h="100%">+ <LoadingAndErrorWrapper loading={isLoading} error={error} />+ </Center>+ );+ }++ return (+ <PageContainer data-testid="data-app-actions" gap="lg">+ <DataAppHeader app={app} />+ <DataAppItemList+ app={app}+ model="action"+ emptyMessage={t`No actions yet`}+ getItemUrl={(actionId) =>+ Urls.dataStudioDataAppAction(app.name, actionId)+ }+ />+ </PageContainer>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppActionsPage/index.ts b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppActionsPage/index.tsnew file mode 100644index 00000000000..96de45997cb--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppActionsPage/index.ts@@ -0,0 +1 @@+export { DataAppActionsPage } from "./DataAppActionsPage";diff --git a/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppListPage/DataAppListEmptyState/DataAppListEmptyState.tsx b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppListPage/DataAppListEmptyState/DataAppListEmptyState.tsxnew file mode 100644index 00000000000..4d4a3e6e46a--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppListPage/DataAppListEmptyState/DataAppListEmptyState.tsx@@ -0,0 +1,35 @@+import { t } from "ttag";++import { FeatureEmptyState } from "metabase/common/data-studio/components/FeatureEmptyState";++export function DataAppListEmptyState() {+ return (+ <FeatureEmptyState+ title={t`Apps built on your semantic layer`}+ description={t`Use the mb CLI to create a data app. Deploy it to your production instance with Remote Sync.`}+ actions={null}+ features={[+ {+ icon: "ai",+ title: t`Built by your AI agent`,+ description: t`Describe the app; your agent writes it`,+ },+ {+ icon: "git_branch",+ title: t`Version control`,+ description: t`Apps live in data_apps/ in your repository`,+ },+ {+ icon: "repository",+ title: t`Your semantic layer`,+ description: t`Reads the tables and metrics you publish`,+ },+ {+ icon: "bolt",+ title: t`Data actions`,+ description: t`Writes go through actions you define`,+ },+ ]}+ />+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppListPage/DataAppListEmptyState/index.ts b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppListPage/DataAppListEmptyState/index.tsnew file mode 100644index 00000000000..85261b524bf--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppListPage/DataAppListEmptyState/index.ts@@ -0,0 +1 @@+export { DataAppListEmptyState } from "./DataAppListEmptyState";diff --git a/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppListPage/DataAppListPage.tsx b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppListPage/DataAppListPage.tsxnew file mode 100644index 00000000000..42a99ac4171--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppListPage/DataAppListPage.tsx@@ -0,0 +1,142 @@+import { useCallback, useMemo, useState } from "react";+import { t } from "ttag";++import { DateTime } from "metabase/common/components/DateTime";+import { ListEmptyState } from "metabase/common/components/ListEmptyState";+import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";+import { DataStudioBreadcrumbs } from "metabase/common/data-studio/components/DataStudioBreadcrumbs";+import { PageContainer } from "metabase/common/data-studio/components/PageContainer";+import { PaneHeader } from "metabase/common/data-studio/components/PaneHeader";+import { useNavigate } from "metabase/router";+import {+ Card,+ Ellipsified,+ Flex,+ Icon,+ Stack,+ TextInput,+ TreeTable,+ type TreeTableColumnDef,+ TreeTableSkeleton,+ useTreeTableInstance,+} from "metabase/ui";+import * as Urls from "metabase/urls";+import { useListDataAppsQuery } from "metabase-enterprise/api";+import type { DataApp } from "metabase-types/api";++import { DataAppMoreMenu } from "../../components/DataAppMoreMenu";+import { getDataAppStatusLabel } from "../../utils";++import { DataAppListEmptyState } from "./DataAppListEmptyState";++export function DataAppListPage() {+ const navigate = useNavigate();+ const [searchQuery, setSearchQuery] = useState("");+ const { data: apps = [], isLoading, error } = useListDataAppsQuery();++ const handleRowActivate = useCallback(+ (row: { original: DataApp }) => {+ navigate(Urls.dataStudioDataApp(row.original.name));+ },+ [navigate],+ );++ const columns = useMemo<TreeTableColumnDef<DataApp>[]>(+ () => [+ {+ id: "name",+ accessorKey: "display_name",+ header: t`Name`,+ minWidth: 160,+ cell: ({ row }) => (+ <Ellipsified>{row.original.display_name}</Ellipsified>+ ),+ },+ {+ id: "address",+ accessorFn: (app) => Urls.dataApp(app.name),+ header: t`Address`,+ minWidth: 160,+ cell: ({ row }) => (+ <Ellipsified>{Urls.dataApp(row.original.name)}</Ellipsified>+ ),+ },+ {+ id: "status",+ accessorFn: (app) => getDataAppStatusLabel(app),+ header: t`Status`,+ minWidth: 120,+ cell: ({ row }) => getDataAppStatusLabel(row.original),+ },+ {+ id: "updated_at",+ accessorKey: "updated_at",+ header: t`Last synced`,+ minWidth: 160,+ cell: ({ row }) => <DateTime value={row.original.updated_at} />,+ },+ {+ id: "actions",+ header: "",+ width: 48,+ cell: ({ row }) => <DataAppMoreMenu app={row.original} />,+ },+ ],+ [],+ );++ const treeTableInstance = useTreeTableInstance({+ data: apps,+ columns,+ getNodeId: (app) => app.name,+ globalFilter: searchQuery,+ onGlobalFilterChange: setSearchQuery,+ onRowActivate: handleRowActivate,+ });++ if (error) {+ return <LoadingAndErrorWrapper loading={false} error={error} />;+ }++ const isEmpty = !isLoading && apps.length === 0;++ return (+ <PageContainer data-testid="data-app-list" gap={0}>+ <PaneHeader+ breadcrumbs={+ <DataStudioBreadcrumbs>{t`Data apps`}</DataStudioBreadcrumbs>+ }+ />+ {isEmpty ? (+ <DataAppListEmptyState />+ ) : (+ <Stack style={{ overflow: "hidden" }}>+ <TextInput+ placeholder={t`Search...`}+ leftSection={<Icon name="search" />}+ bdrs="sm"+ value={searchQuery}+ onChange={(event) => setSearchQuery(event.target.value)}+ />+ <Flex direction="column" flex={1} mih={0}>+ <Card withBorder p={0}>+ {isLoading ? (+ <TreeTableSkeleton columnWidths={[0.3, 0.3, 0.15, 0.2, 0.05]} />+ ) : (+ <TreeTable+ instance={treeTableInstance}+ emptyState={+ searchQuery ? (+ <ListEmptyState label={t`No data apps found`} />+ ) : null+ }+ onRowClick={handleRowActivate}+ />+ )}+ </Card>+ </Flex>+ </Stack>+ )}+ </PageContainer>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppListPage/DataAppListPage.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppListPage/DataAppListPage.unit.spec.tsxnew file mode 100644index 00000000000..0c5742f41e3--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppListPage/DataAppListPage.unit.spec.tsx@@ -0,0 +1,59 @@+import { setupListDataAppsEndpoint } from "__support__/server-mocks";+import {+ mockGetBoundingClientRect,+ renderWithProviders,+ screen,+} from "__support__/ui";+import type { DataApp } from "metabase-types/api";+import { createMockDataApp } from "metabase-types/api/mocks";++import { DataAppListPage } from "./DataAppListPage";++type SetupOpts = {+ apps: DataApp[];+};++function setup({ apps }: SetupOpts) {+ setupListDataAppsEndpoint(apps);+ renderWithProviders(<DataAppListPage />, { withRouter: true });+}++describe("DataAppListPage", () => {+ beforeEach(() => {+ mockGetBoundingClientRect({ width: 1000, height: 1000 });+ });++ it("lists the apps with their address and status", async () => {+ setup({+ apps: [+ createMockDataApp({+ name: "order-desk",+ display_name: "Order desk",+ enabled: true,+ }),+ createMockDataApp({+ id: 2,+ name: "inventory",+ display_name: "Inventory",+ enabled: true,+ outdated: true,+ }),+ ],+ });++ expect(await screen.findByText("Order desk")).toBeInTheDocument();+ expect(screen.getByText("/apps/order-desk")).toBeInTheDocument();+ expect(screen.getByText("Live")).toBeInTheDocument();+ expect(screen.getByText("Live, outdated")).toBeInTheDocument();+ });++ it("explains how to create a data app when there are none", async () => {+ setup({ apps: [] });++ expect(+ await screen.findByText(+ "Use the mb CLI to create a data app. Deploy it to your production instance with Remote Sync.",+ ),+ ).toBeInTheDocument();+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppListPage/index.ts b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppListPage/index.tsnew file mode 100644index 00000000000..a5a2688b3eb--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppListPage/index.ts@@ -0,0 +1 @@+export { DataAppListPage } from "./DataAppListPage";diff --git a/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppOverviewPage/DataAppAboutSidebar/DataAppAboutSidebar.tsx b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppOverviewPage/DataAppAboutSidebar/DataAppAboutSidebar.tsxnew file mode 100644index 00000000000..e70fdb61c19--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppOverviewPage/DataAppAboutSidebar/DataAppAboutSidebar.tsx@@ -0,0 +1,73 @@+import { t } from "ttag";++import { Markdown } from "metabase/common/components/Markdown";+import { AboutSidebar } from "metabase/common/data-studio/components/AboutSidebar";+import { AboutHeader } from "metabase/common/data-studio/components/AboutSidebar/AboutHeader";+import { AboutSubSection } from "metabase/common/data-studio/components/AboutSidebar/AboutSubSection";+import { MetadataCard } from "metabase/common/data-studio/components/AboutSidebar/MetadataCard";+import { MetadataRow } from "metabase/common/data-studio/components/AboutSidebar/MetadataRow";+import { MetadataRowLink } from "metabase/common/data-studio/components/AboutSidebar/MetadataRowLink";+import { Box } from "metabase/ui";+import * as Urls from "metabase/urls";+import { useGetDataAppGroupsQuery } from "metabase-enterprise/api";+import type { DataApp } from "metabase-types/api";++import { isDataAppOpenable } from "../../../utils";++type DataAppAboutSidebarProps = {+ app: DataApp;+};++export function DataAppAboutSidebar({ app }: DataAppAboutSidebarProps) {+ const { data: groups = [] } = useGetDataAppGroupsQuery(app.name);+ const appUrl = Urls.dataApp(app.name);++ return (+ <AboutSidebar flex="0 0 360px" data-testid="data-app-about-sidebar">+ <AboutHeader updatedAt={app.updated_at} />+ <Box mt="lg">+ <Markdown>{app.description || t`No description`}</Markdown>+ </Box>+ <AboutSubSection title={t`Status`} mt="xxl">+ <MetadataCard>+ <MetadataRow icon={app.enabled ? "eye" : "eye_crossed_out"}>+ {app.enabled ? t`Live` : t`Draft`}+ </MetadataRow>+ {app.outdated && (+ <MetadataRow icon="warning">{t`Outdated`}</MetadataRow>+ )}+ </MetadataCard>+ </AboutSubSection>+ <AboutSubSection title={t`Address`} mt="xxl">+ <MetadataCard>+ <MetadataRow icon="link">+ {isDataAppOpenable(app) ? (+ <MetadataRowLink to={appUrl}>{appUrl}</MetadataRowLink>+ ) : (+ appUrl+ )}+ </MetadataRow>+ </MetadataCard>+ </AboutSubSection>+ <AboutSubSection title={t`Group access`} mt="xxl">+ <MetadataCard>+ {groups.length > 0 ? (+ groups.map((group) => (+ <MetadataRow key={group.id} icon="group">+ <MetadataRowLink+ to={Urls.dataStudioDataAppPermissions(app.name)}+ >+ {group.name}+ </MetadataRowLink>+ </MetadataRow>+ ))+ ) : (+ <MetadataRow icon="group" muted>+ {t`No groups`}+ </MetadataRow>+ )}+ </MetadataCard>+ </AboutSubSection>+ </AboutSidebar>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppOverviewPage/DataAppAboutSidebar/index.ts b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppOverviewPage/DataAppAboutSidebar/index.tsnew file mode 100644index 00000000000..3bec59d7bf7--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppOverviewPage/DataAppAboutSidebar/index.ts@@ -0,0 +1 @@+export { DataAppAboutSidebar } from "./DataAppAboutSidebar";diff --git a/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppOverviewPage/DataAppOverviewPage.tsx b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppOverviewPage/DataAppOverviewPage.tsxnew file mode 100644index 00000000000..28602d9f259--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppOverviewPage/DataAppOverviewPage.tsx@@ -0,0 +1,33 @@+import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";+import { PageContainer } from "metabase/common/data-studio/components/PageContainer";+import { Card, Center, Flex } from "metabase/ui";++import { DataAppView } from "../../../host/components/DataAppView/DataAppView";+import { DataAppHeader } from "../../components/DataAppHeader";+import { useRouteDataApp } from "../../hooks/use-route-data-app";++import { DataAppAboutSidebar } from "./DataAppAboutSidebar";++export function DataAppOverviewPage() {+ const { app, isLoading, error } = useRouteDataApp();++ if (isLoading || error != null || app == null) {+ return (+ <Center h="100%">+ <LoadingAndErrorWrapper loading={isLoading} error={error} />+ </Center>+ );+ }++ return (+ <PageContainer data-testid="data-app-overview">+ <DataAppHeader app={app} />+ <Flex flex={1} gap="lg" mih={0}>+ <Card withBorder p="xl" flex={1} mah={700}>+ <DataAppView name={app.name} enableDrafts />+ </Card>+ <DataAppAboutSidebar app={app} />+ </Flex>+ </PageContainer>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppOverviewPage/index.ts b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppOverviewPage/index.tsnew file mode 100644index 00000000000..69d7a135317--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppOverviewPage/index.ts@@ -0,0 +1 @@+export { DataAppOverviewPage } from "./DataAppOverviewPage";diff --git a/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppPermissionsPage/AddDataAppGroupsModal/AddDataAppGroupsModal.tsx b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppPermissionsPage/AddDataAppGroupsModal/AddDataAppGroupsModal.tsxnew file mode 100644index 00000000000..5cf3f607abb--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppPermissionsPage/AddDataAppGroupsModal/AddDataAppGroupsModal.tsx@@ -0,0 +1,97 @@+import { useMemo, useState } from "react";+import { t } from "ttag";++import { useListPermissionsGroupsQuery } from "metabase/api";+import { useMetadataToasts } from "metabase/common/hooks";+import {+ getGroupNameLocalized,+ isAdminGroup,+} from "metabase/common/utils/groups";+import { Button, Group, Modal, MultiSelect, Stack, Text } from "metabase/ui";+import {+ useAddDataAppGroupsMutation,+ useGetDataAppGroupsQuery,+} from "metabase-enterprise/api";+import type { DataApp } from "metabase-types/api";++const DROPDOWN_WIDTH = 300;++type AddDataAppGroupsModalProps = {+ app: DataApp;+ onClose: () => void;+};++export function AddDataAppGroupsModal({+ app,+ onClose,+}: AddDataAppGroupsModalProps) {+ const [selectedIds, setSelectedIds] = useState<string[]>([]);+ const { data: assignedGroups = [] } = useGetDataAppGroupsQuery(app.name);+ const { data: groups, isLoading } = useListPermissionsGroupsQuery({+ tenancy: "internal",+ });+ const [addGroups, { isLoading: isAdding }] = useAddDataAppGroupsMutation();+ const { sendErrorToast } = useMetadataToasts();++ const options = useMemo(+ () =>+ groups+ ?.filter(+ (group) =>+ !group.is_tenant_group &&+ !isAdminGroup(group) &&+ !assignedGroups.some((assigned) => assigned.id === group.id),+ )+ .map((group) => ({+ value: String(group.id),+ label: getGroupNameLocalized(group),+ })),+ [groups, assignedGroups],+ );++ const handleAdd = async () => {+ const { error } = await addGroups({+ name: app.name,+ group_ids: selectedIds.map(Number),+ });+ if (error) {+ sendErrorToast(t`Failed to add groups`);+ } else {+ onClose();+ }+ };++ return (+ <Modal+ title={t`Add groups to ${app.display_name}`}+ opened+ onClose={onClose}+ >+ <Stack gap="lg" mt="sm">+ <Text>{t`People in these groups will be able to open the app.`}</Text>+ <MultiSelect+ aria-label={t`Groups`}+ placeholder={t`Search for groups to add`}+ searchable+ comboboxProps={{ width: DROPDOWN_WIDTH, position: "bottom-start" }}+ data={options}+ value={selectedIds}+ onChange={setSelectedIds}+ disabled={isLoading}+ data-autofocus+ />+ <Group justify="flex-end" gap="md">+ <Button onClick={onClose}>{t`Cancel`}</Button>+ <Button+ variant="filled"+ loading={isAdding}+ disabled={selectedIds.length === 0}+ onClick={handleAdd}+ >+ {t`Add`}+ </Button>+ </Group>+ </Stack>+ </Modal>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppPermissionsPage/AddDataAppGroupsModal/AddDataAppGroupsModal.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppPermissionsPage/AddDataAppGroupsModal/AddDataAppGroupsModal.unit.spec.tsxnew file mode 100644index 00000000000..f4337b514c6--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppPermissionsPage/AddDataAppGroupsModal/AddDataAppGroupsModal.unit.spec.tsx@@ -0,0 +1,85 @@+import userEvent from "@testing-library/user-event";+import fetchMock from "fetch-mock";++import {+ setupAddDataAppGroupsEndpoint,+ setupDataAppGroupsEndpoint,+ setupGroupsEndpoint,+} from "__support__/server-mocks";+import { renderWithProviders, screen, waitFor } from "__support__/ui";+import {+ createMockDataApp,+ createMockDataAppGroup,+ createMockGroup,+} from "metabase-types/api/mocks";++import { AddDataAppGroupsModal } from "./AddDataAppGroupsModal";++function setup() {+ setupGroupsEndpoint([+ createMockGroup({+ id: 1,+ name: "All Users",+ magic_group_type: "all-internal-users",+ }),+ createMockGroup({+ id: 2,+ name: "Administrators",+ magic_group_type: "admin",+ }),+ createMockGroup({ id: 3, name: "Support" }),+ createMockGroup({ id: 4, name: "Finance" }),+ ]);+ const support = createMockDataAppGroup({+ id: 3,+ name: "Support",+ member_count: 12,+ });+ setupDataAppGroupsEndpoint("sales", [support]);+ setupAddDataAppGroupsEndpoint("sales", [+ support,+ createMockDataAppGroup({ id: 4, name: "Finance", member_count: 4 }),+ ]);+ const onClose = jest.fn<void, []>();+ renderWithProviders(+ <AddDataAppGroupsModal+ app={createMockDataApp({ name: "sales", display_name: "Sales" })}+ onClose={onClose}+ />,+ );+ return { onClose };+}++describe("AddDataAppGroupsModal", () => {+ it("offers only groups the app doesn't have and adds the selected ones", async () => {+ const { onClose } = setup();++ expect(await screen.findByText("Add groups to Sales")).toBeInTheDocument();+ await userEvent.click(screen.getByRole("textbox", { name: "Groups" }));++ expect(+ await screen.findByRole("option", { name: "Finance" }),+ ).toBeInTheDocument();+ expect(+ screen.queryByRole("option", { name: "Support" }),+ ).not.toBeInTheDocument();+ expect(+ screen.queryByRole("option", { name: "Administrators" }),+ ).not.toBeInTheDocument();++ await userEvent.click(screen.getByRole("option", { name: "Finance" }));+ await userEvent.click(screen.getByRole("button", { name: "Add" }));++ await waitFor(() => expect(onClose).toHaveBeenCalled());+ const calls = fetchMock.callHistory.calls(+ "path:/api/ee/apps/sales/groups",+ {+ method: "POST",+ },+ );+ expect(calls).toHaveLength(1);+ expect(JSON.parse(String(calls[0].options.body))).toEqual({+ group_ids: [4],+ });+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppPermissionsPage/AddDataAppGroupsModal/index.ts b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppPermissionsPage/AddDataAppGroupsModal/index.tsnew file mode 100644index 00000000000..65bbf93b2f3--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppPermissionsPage/AddDataAppGroupsModal/index.ts@@ -0,0 +1 @@+export { AddDataAppGroupsModal } from "./AddDataAppGroupsModal";diff --git a/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppPermissionsPage/DataAppGroupList/DataAppGroupDataAccess/DataAppGroupDataAccess.tsx b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppPermissionsPage/DataAppGroupList/DataAppGroupDataAccess/DataAppGroupDataAccess.tsxnew file mode 100644index 00000000000..654e3141dae--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppPermissionsPage/DataAppGroupList/DataAppGroupDataAccess/DataAppGroupDataAccess.tsx@@ -0,0 +1,40 @@+import { msgid, ngettext, t } from "ttag";++import { Box } from "metabase/ui";+import { EMPTY_CELL_PLACEHOLDER } from "metabase/utils/constants";+import { useGetDataAppGroupPermissionWarningsQuery } from "metabase-enterprise/api";+import type { DataApp, DataAppGroup } from "metabase-types/api";++type DataAppGroupDataAccessProps = {+ app: DataApp;+ group: DataAppGroup;+};++export function DataAppGroupDataAccess({+ app,+ group,+}: DataAppGroupDataAccessProps) {+ const { data: warnings } = useGetDataAppGroupPermissionWarningsQuery(+ app.name,+ );++ if (warnings == null) {+ return EMPTY_CELL_PLACEHOLDER;+ }++ const warning = warnings.find(({ group_id }) => group_id === group.id);+ if (warning == null) {+ return t`All tables`;+ }++ const tableCount = warning.missing_tables.length;+ return (+ <Box c="feedback-negative">+ {ngettext(+ msgid`Missing ${tableCount} table`,+ `Missing ${tableCount} tables`,+ tableCount,+ )}+ </Box>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppPermissionsPage/DataAppGroupList/DataAppGroupDataAccess/index.ts b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppPermissionsPage/DataAppGroupList/DataAppGroupDataAccess/index.tsnew file mode 100644index 00000000000..d4e51795ed1--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppPermissionsPage/DataAppGroupList/DataAppGroupDataAccess/index.ts@@ -0,0 +1 @@+export { DataAppGroupDataAccess } from "./DataAppGroupDataAccess";diff --git a/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppPermissionsPage/DataAppGroupList/DataAppGroupList.tsx b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppPermissionsPage/DataAppGroupList/DataAppGroupList.tsxnew file mode 100644index 00000000000..e4d518d7664--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppPermissionsPage/DataAppGroupList/DataAppGroupList.tsx@@ -0,0 +1,105 @@+import { useMemo } from "react";+import { t } from "ttag";++import { ListEmptyState } from "metabase/common/components/ListEmptyState";+import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";+import { getGroupNameLocalized } from "metabase/common/utils/groups";+import {+ Card,+ Ellipsified,+ Flex,+ TreeTable,+ type TreeTableColumnDef,+ TreeTableSkeleton,+ useTreeTableInstance,+} from "metabase/ui";+import { useGetDataAppGroupsQuery } from "metabase-enterprise/api";+import type { DataApp, DataAppGroup, GroupId } from "metabase-types/api";++import { DataAppGroupDataAccess } from "./DataAppGroupDataAccess";+import { DataAppGroupMenu } from "./DataAppGroupMenu";++type DataAppGroupListProps = {+ app: DataApp;+ selectedGroupId: GroupId | undefined;+ onSelectGroup: (groupId: GroupId) => void;+};++export function DataAppGroupList({+ app,+ selectedGroupId,+ onSelectGroup,+}: DataAppGroupListProps) {+ const {+ data: groups = [],+ isLoading,+ error,+ } = useGetDataAppGroupsQuery(app.name);++ const columns = useMemo<TreeTableColumnDef<DataAppGroup>[]>(+ () => [+ {+ id: "name",+ accessorFn: (group) => getGroupNameLocalized(group),+ header: t`Group name`,+ minWidth: 200,+ cell: ({ row }) => (+ <Ellipsified>{getGroupNameLocalized(row.original)}</Ellipsified>+ ),+ },+ {+ id: "member_count",+ accessorKey: "member_count",+ header: t`Members`,+ minWidth: 120,+ },+ {+ id: "data_access",+ header: t`Data access`,+ minWidth: 200,+ cell: ({ row }) => (+ <DataAppGroupDataAccess app={app} group={row.original} />+ ),+ },+ {+ id: "actions",+ header: "",+ width: 48,+ cell: ({ row }) => <DataAppGroupMenu app={app} group={row.original} />,+ },+ ],+ [app],+ );++ const treeTableInstance = useTreeTableInstance({+ data: groups,+ columns,+ getNodeId: (group) => String(group.id),+ selectedRowId: selectedGroupId != null ? String(selectedGroupId) : null,+ onRowActivate: (row) => onSelectGroup(row.original.id),+ });++ if (error) {+ return <LoadingAndErrorWrapper loading={false} error={error} />;+ }++ return (+ <Flex direction="column" flex={1} mih={0}>+ <Card withBorder p={0}>+ {isLoading ? (+ <TreeTableSkeleton columnWidths={[0.4, 0.2, 0.35, 0.05]} />+ ) : (+ <TreeTable+ instance={treeTableInstance}+ onRowClick={(row) => onSelectGroup(row.original.id)}+ emptyState={+ <ListEmptyState+ label={t`Only admins can open this app. Add groups to give people in them access.`}+ />+ }+ />+ )}+ </Card>+ </Flex>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppPermissionsPage/DataAppGroupList/DataAppGroupList.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppPermissionsPage/DataAppGroupList/DataAppGroupList.unit.spec.tsxnew file mode 100644index 00000000000..d59029be5fc--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppPermissionsPage/DataAppGroupList/DataAppGroupList.unit.spec.tsx@@ -0,0 +1,127 @@+import userEvent from "@testing-library/user-event";+import fetchMock from "fetch-mock";++import {+ setupDataAppGroupPermissionWarningsEndpoint,+ setupDataAppGroupsEndpoint,+ setupRemoveDataAppGroupEndpoint,+} from "__support__/server-mocks";+import {+ mockGetBoundingClientRect,+ renderWithProviders,+ screen,+ within,+} from "__support__/ui";+import type {+ DataAppGroup,+ DataAppGroupPermissionWarning,+ GroupId,+} from "metabase-types/api";+import {+ createMockDataApp,+ createMockDataAppGroup,+ createMockDataAppGroupPermissionWarning,+} from "metabase-types/api/mocks";++import { DataAppGroupList } from "./DataAppGroupList";++type SetupOpts = {+ groups: DataAppGroup[];+ warnings?: DataAppGroupPermissionWarning[];+};++function setup({ groups, warnings = [] }: SetupOpts) {+ const onSelectGroup = jest.fn<void, [GroupId]>();+ setupDataAppGroupsEndpoint("sales", groups);+ setupDataAppGroupPermissionWarningsEndpoint("sales", warnings);+ groups.forEach((group) => setupRemoveDataAppGroupEndpoint("sales", group.id));+ renderWithProviders(+ <DataAppGroupList+ app={createMockDataApp({ name: "sales", display_name: "Sales" })}+ selectedGroupId={undefined}+ onSelectGroup={onSelectGroup}+ />,+ );+ return { onSelectGroup };+}++describe("DataAppGroupList", () => {+ beforeEach(() => {+ mockGetBoundingClientRect({ width: 1000, height: 1000 });+ });++ it("lists the groups with their members and missing data access", async () => {+ setup({+ groups: [+ createMockDataAppGroup({ id: 3, name: "Support", member_count: 12 }),+ createMockDataAppGroup({ id: 4, name: "Finance", member_count: 4 }),+ ],+ warnings: [createMockDataAppGroupPermissionWarning({ group_id: 4 })],+ });++ expect(await screen.findByText("Support")).toBeInTheDocument();+ expect(screen.getByText("12")).toBeInTheDocument();+ expect(screen.getByText("Finance")).toBeInTheDocument();+ expect(await screen.findByText("Missing 1 table")).toBeInTheDocument();+ expect(screen.getByText("All tables")).toBeInTheDocument();+ });++ it("selects a group when its row is clicked", async () => {+ const { onSelectGroup } = setup({+ groups: [createMockDataAppGroup({ id: 3, name: "Support" })],+ });++ await userEvent.click(await screen.findByText("Support"));++ expect(onSelectGroup).toHaveBeenCalledWith(3);+ });++ it("says only admins can open an app without groups", async () => {+ setup({ groups: [] });++ expect(+ await screen.findByText(+ "Only admins can open this app. Add groups to give people in them access.",+ ),+ ).toBeInTheDocument();+ });++ it("links to the group and removes its access after confirmation", async () => {+ setup({+ groups: [+ createMockDataAppGroup({ id: 3, name: "Support", member_count: 12 }),+ ],+ });++ await userEvent.click(+ await screen.findByRole("button", { name: "Support options" }),+ );+ expect(+ await screen.findByRole("menuitem", { name: /View group/ }),+ ).toHaveAttribute("href", "/admin/people/groups/3");++ await userEvent.click(+ screen.getByRole("menuitem", { name: /Remove access/ }),+ );++ const dialog = await screen.findByRole("dialog");+ expect(+ within(dialog).getByText("Remove Support from Sales?"),+ ).toBeInTheDocument();+ expect(+ fetchMock.callHistory.calls("path:/api/ee/apps/sales/groups/3", {+ method: "DELETE",+ }),+ ).toHaveLength(0);++ await userEvent.click(+ within(dialog).getByRole("button", { name: "Remove access" }),+ );++ expect(+ fetchMock.callHistory.calls("path:/api/ee/apps/sales/groups/3", {+ method: "DELETE",+ }),+ ).toHaveLength(1);+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppPermissionsPage/DataAppGroupList/DataAppGroupMenu/DataAppGroupMenu.tsx b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppPermissionsPage/DataAppGroupList/DataAppGroupMenu/DataAppGroupMenu.tsxnew file mode 100644index 00000000000..d372f4ee141--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppPermissionsPage/DataAppGroupList/DataAppGroupMenu/DataAppGroupMenu.tsx@@ -0,0 +1,66 @@+import { t } from "ttag";++import { MoreMenuButton } from "metabase/common/data-studio/components/MoreMenuButton";+import { useConfirmation, useMetadataToasts } from "metabase/common/hooks";+import { getGroupNameLocalized } from "metabase/common/utils/groups";+import { Icon, Menu } from "metabase/ui";+import * as Urls from "metabase/urls";+import { useRemoveDataAppGroupMutation } from "metabase-enterprise/api";+import type { DataApp, DataAppGroup } from "metabase-types/api";++type DataAppGroupMenuProps = {+ app: DataApp;+ group: DataAppGroup;+};++export function DataAppGroupMenu({ app, group }: DataAppGroupMenuProps) {+ const [removeGroup] = useRemoveDataAppGroupMutation();+ const { sendErrorToast } = useMetadataToasts();+ const { show: showConfirmation, modalContent } = useConfirmation();+ const groupName = getGroupNameLocalized(group);++ const handleRemove = () => {+ showConfirmation({+ title: t`Remove ${groupName} from ${app.display_name}?`,+ message: t`People in this group will no longer be able to open the app, unless another of their groups has access.`,+ confirmButtonText: t`Remove access`,+ onConfirm: async () => {+ const { error } = await removeGroup({+ name: app.name,+ group_id: group.id,+ });+ if (error) {+ sendErrorToast(t`Failed to remove ${groupName}`);+ }+ },+ });+ };++ return (+ <>+ <Menu position="bottom-end">+ <Menu.Target>+ <MoreMenuButton+ aria-label={t`${groupName} options`}+ onClick={(event) => event.stopPropagation()}+ />+ </Menu.Target>+ <Menu.Dropdown onClick={(event) => event.stopPropagation()}>+ <Menu.Item+ component="a"+ href={Urls.getSubpathSafeUrl(Urls.adminGroup(group.id))}+ target="_blank"+ rel="noreferrer"+ leftSection={<Icon name="external" />}+ >+ {t`View group`}+ </Menu.Item>+ <Menu.Item leftSection={<Icon name="trash" />} onClick={handleRemove}>+ {t`Remove access`}+ </Menu.Item>+ </Menu.Dropdown>+ </Menu>+ {modalContent}+ </>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppPermissionsPage/DataAppGroupList/DataAppGroupMenu/index.ts b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppPermissionsPage/DataAppGroupList/DataAppGroupMenu/index.tsnew file mode 100644index 00000000000..0735abb6dff--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppPermissionsPage/DataAppGroupList/DataAppGroupMenu/index.ts@@ -0,0 +1 @@+export { DataAppGroupMenu } from "./DataAppGroupMenu";diff --git a/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppPermissionsPage/DataAppGroupList/index.ts b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppPermissionsPage/DataAppGroupList/index.tsnew file mode 100644index 00000000000..ccb889bc533--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppPermissionsPage/DataAppGroupList/index.ts@@ -0,0 +1 @@+export { DataAppGroupList } from "./DataAppGroupList";diff --git a/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppPermissionsPage/DataAppGroupSidebar/DataAppGroupSidebar.module.css b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppPermissionsPage/DataAppGroupSidebar/DataAppGroupSidebar.module.cssnew file mode 100644index 00000000000..77c6b127301--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppPermissionsPage/DataAppGroupSidebar/DataAppGroupSidebar.module.css@@ -0,0 +1,5 @@+.sidebar {+ flex: 1 1 auto;+ overflow: auto;+ border-left: 1px solid var(--mb-color-border-neutral);+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppPermissionsPage/DataAppGroupSidebar/DataAppGroupSidebar.tsx b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppPermissionsPage/DataAppGroupSidebar/DataAppGroupSidebar.tsxnew file mode 100644index 00000000000..3300a5d6b02--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppPermissionsPage/DataAppGroupSidebar/DataAppGroupSidebar.tsx@@ -0,0 +1,113 @@+import cx from "classnames";+import { t } from "ttag";++import { ForwardRefLink } from "metabase/common/components/Link";+import { SidebarResizableBox } from "metabase/common/components/SidebarResizableBox";+import { getGroupNameLocalized } from "metabase/common/utils/groups";+import CS from "metabase/css/core/index.css";+import {+ ActionIcon,+ Box,+ Card,+ FixedSizeIcon,+ Group,+ Stack,+ Title,+ Tooltip,+} from "metabase/ui";+import * as Urls from "metabase/urls";+import { useGetDataAppGroupPermissionWarningsQuery } from "metabase-enterprise/api";+import type { DataApp, DataAppGroup } from "metabase-types/api";++import S from "./DataAppGroupSidebar.module.css";+import { MissingTablesSection } from "./MissingTablesSection";++type DataAppGroupSidebarProps = {+ app: DataApp;+ group: DataAppGroup;+ containerWidth: number;+ onResizeStart: () => void;+ onResizeStop: () => void;+ onClose: () => void;+};++export function DataAppGroupSidebar({+ app,+ group,+ containerWidth,+ onResizeStart,+ onResizeStop,+ onClose,+}: DataAppGroupSidebarProps) {+ const { data: warnings } = useGetDataAppGroupPermissionWarningsQuery(+ app.name,+ );+ const warning = warnings?.find(({ group_id }) => group_id === group.id);+ const groupUrl = Urls.adminGroup(group.id);++ return (+ <SidebarResizableBox+ containerWidth={containerWidth}+ onResizeStart={onResizeStart}+ onResizeStop={onResizeStop}+ >+ <Stack+ className={S.sidebar}+ p="xl"+ gap="xxl"+ bg="background_page-primary"+ data-testid="data-app-group-sidebar"+ >+ <Stack gap="xl">+ <Group+ gap="0.75rem"+ wrap="nowrap"+ align="start"+ justify="space-between"+ >+ <Title className={cx(CS.textWrap)} order={3}>+ {getGroupNameLocalized(group)}+ </Title>+ <Group gap="xxs" wrap="nowrap">+ <Tooltip label={t`View group`}>+ <ActionIcon+ variant="subtle"+ component={ForwardRefLink}+ to={groupUrl}+ target="_blank"+ aria-label={t`View group`}+ >+ <FixedSizeIcon name="external" />+ </ActionIcon>+ </Tooltip>+ <ActionIcon+ variant="subtle"+ aria-label={t`Close`}+ onClick={onClose}+ >+ <FixedSizeIcon name="close" />+ </ActionIcon>+ </Group>+ </Group>+ <Card+ p={0}+ shadow="none"+ withBorder+ role="region"+ aria-label={t`Info`}+ >+ <Stack p="lg" gap="xxs">+ <Box c="text-secondary" fz="sm" lh="h5">+ {t`Members`}+ </Box>+ <Box lh="h4">{group.member_count}</Box>+ </Stack>+ </Card>+ </Stack>+ {warning != null && warning.missing_tables.length > 0 && (+ <MissingTablesSection tables={warning.missing_tables} />+ )}+ </Stack>+ </SidebarResizableBox>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppPermissionsPage/DataAppGroupSidebar/DataAppGroupSidebar.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppPermissionsPage/DataAppGroupSidebar/DataAppGroupSidebar.unit.spec.tsxnew file mode 100644index 00000000000..722ec9e78d8--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppPermissionsPage/DataAppGroupSidebar/DataAppGroupSidebar.unit.spec.tsx@@ -0,0 +1,107 @@+import userEvent from "@testing-library/user-event";++import { setupDataAppGroupPermissionWarningsEndpoint } from "__support__/server-mocks";+import { renderWithProviders, screen, within } from "__support__/ui";+import type {+ DataAppGroup,+ DataAppGroupPermissionWarning,+} from "metabase-types/api";+import {+ createMockDataApp,+ createMockDataAppGroup,+ createMockDataAppGroupPermissionWarning,+ createMockDataAppMissingTable,+} from "metabase-types/api/mocks";++import { DataAppGroupSidebar } from "./DataAppGroupSidebar";++type SetupOpts = {+ group: DataAppGroup;+ warnings?: DataAppGroupPermissionWarning[];+};++function setup({ group, warnings = [] }: SetupOpts) {+ setupDataAppGroupPermissionWarningsEndpoint("sales", warnings);+ const onClose = jest.fn<void, []>();+ renderWithProviders(+ <DataAppGroupSidebar+ app={createMockDataApp({ name: "sales" })}+ group={group}+ containerWidth={1200}+ onResizeStart={jest.fn<void, []>()}+ onResizeStop={jest.fn<void, []>()}+ onClose={onClose}+ />,+ );+ return { onClose };+}++describe("DataAppGroupSidebar", () => {+ it("shows the group with its members and a link to it", async () => {+ setup({+ group: createMockDataAppGroup({+ id: 3,+ name: "Support",+ member_count: 12,+ }),+ });++ expect(+ await screen.findByRole("heading", { name: "Support" }),+ ).toBeInTheDocument();+ expect(+ within(screen.getByRole("region", { name: "Info" })).getByText("12"),+ ).toBeInTheDocument();+ expect(screen.getByRole("link", { name: "View group" })).toHaveAttribute(+ "href",+ "/admin/people/groups/3",+ );+ expect(+ screen.queryByRole("region", { name: "Missing tables" }),+ ).not.toBeInTheDocument();+ });++ it("lists the tables the group can't view, each with a link to its permissions", async () => {+ setup({+ group: createMockDataAppGroup({ id: 4, name: "Finance" }),+ warnings: [+ createMockDataAppGroupPermissionWarning({+ group_id: 4,+ missing_tables: [+ createMockDataAppMissingTable({+ id: 10,+ name: "Orders",+ schema: "public",+ database_id: 1,+ database_name: "Shop",+ }),+ ],+ }),+ ],+ });++ const section = await screen.findByRole("region", {+ name: "Missing tables",+ });+ expect(within(section).getByText("Orders")).toBeInTheDocument();+ expect(within(section).getByText("Shop")).toBeInTheDocument();+ expect(within(section).getByText("public")).toBeInTheDocument();++ await userEvent.click(within(section).getByText("Orders"));++ expect(+ await screen.findByRole("menuitem", { name: /Change permissions/ }),+ ).toHaveAttribute(+ "href",+ "/admin/permissions/data/database/1/schema/public/table/10",+ );+ });++ it("closes", async () => {+ const { onClose } = setup({ group: createMockDataAppGroup() });++ await userEvent.click(await screen.findByRole("button", { name: "Close" }));++ expect(onClose).toHaveBeenCalled();+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppPermissionsPage/DataAppGroupSidebar/MissingTablesSection/MissingTablesSection.module.css b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppPermissionsPage/DataAppGroupSidebar/MissingTablesSection/MissingTablesSection.module.cssnew file mode 100644index 00000000000..769ffa2618d--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppPermissionsPage/DataAppGroupSidebar/MissingTablesSection/MissingTablesSection.module.css@@ -0,0 +1,12 @@+.item {+ cursor: pointer;++ &:hover,+ &.active {+ background-color: var(--mb-color-background_page-secondary);+ }++ &:not(:last-child) {+ border-bottom: 1px solid var(--mb-color-border-neutral);+ }+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppPermissionsPage/DataAppGroupSidebar/MissingTablesSection/MissingTablesSection.tsx b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppPermissionsPage/DataAppGroupSidebar/MissingTablesSection/MissingTablesSection.tsxnew file mode 100644index 00000000000..3e0604288f8--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppPermissionsPage/DataAppGroupSidebar/MissingTablesSection/MissingTablesSection.tsx@@ -0,0 +1,100 @@+import cx from "classnames";+import { useState } from "react";+import { t } from "ttag";++import { getDatabaseFocusPermissionsUrl } from "metabase/admin/permissions/utils/urls";+import { ForwardRefLink } from "metabase/common/components/Link";+import CS from "metabase/css/core/index.css";+import {+ Badge,+ Box,+ Breadcrumbs,+ Card,+ FixedSizeIcon,+ Group,+ Menu,+ Stack,+ Title,+} from "metabase/ui";+import type { DataAppMissingTable } from "metabase-types/api";++import S from "./MissingTablesSection.module.css";++type MissingTablesSectionProps = {+ tables: DataAppMissingTable[];+};++export function MissingTablesSection({ tables }: MissingTablesSectionProps) {+ return (+ <Stack role="region" aria-label={t`Missing tables`}>+ <Group gap="sm" wrap="nowrap">+ <Badge color="negative" size="sm">+ {tables.length}+ </Badge>+ <Title order={5}>{t`Missing tables`}</Title>+ </Group>+ <Card p={0} shadow="none" withBorder>+ {tables.map((table) => (+ <MissingTableItem key={table.id} table={table} />+ ))}+ </Card>+ </Stack>+ );+}++type MissingTableItemProps = {+ table: DataAppMissingTable;+};++function MissingTableItem({ table }: MissingTableItemProps) {+ const [isOpened, setIsOpened] = useState(false);+ const location = [table.database_name, table.schema].filter(+ (part) => part != null,+ );++ return (+ <Menu opened={isOpened} onChange={setIsOpened}>+ <Menu.Target>+ <Stack+ className={cx(S.item, { [S.active]: isOpened })}+ p="lg"+ gap="sm"+ aria-label={table.name}+ >+ <Group gap="sm" wrap="nowrap">+ <FixedSizeIcon name="table" />+ <Box className={CS.textWrap} lh="1rem">+ {table.name}+ </Box>+ </Group>+ <Breadcrumbs+ separator={<FixedSizeIcon name="chevronright" size={12} />}+ c="text-secondary"+ ml="1rem"+ pl="sm"+ >+ {location.map((part) => (+ <Box key={part} className={CS.textWrap} lh="1rem">+ {part}+ </Box>+ ))}+ </Breadcrumbs>+ </Stack>+ </Menu.Target>+ <Menu.Dropdown>+ <Menu.Item+ component={ForwardRefLink}+ to={getDatabaseFocusPermissionsUrl({+ databaseId: table.database_id,+ schemaName: table.schema ?? undefined,+ tableId: table.id,+ })}+ target="_blank"+ leftSection={<FixedSizeIcon name="external" />}+ >+ {t`Change permissions`}+ </Menu.Item>+ </Menu.Dropdown>+ </Menu>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppPermissionsPage/DataAppGroupSidebar/MissingTablesSection/index.ts b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppPermissionsPage/DataAppGroupSidebar/MissingTablesSection/index.tsnew file mode 100644index 00000000000..6a63620560e--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppPermissionsPage/DataAppGroupSidebar/MissingTablesSection/index.ts@@ -0,0 +1 @@+export { MissingTablesSection } from "./MissingTablesSection";diff --git a/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppPermissionsPage/DataAppGroupSidebar/index.ts b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppPermissionsPage/DataAppGroupSidebar/index.tsnew file mode 100644index 00000000000..e4332a12ff6--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppPermissionsPage/DataAppGroupSidebar/index.ts@@ -0,0 +1 @@+export { DataAppGroupSidebar } from "./DataAppGroupSidebar";diff --git a/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppPermissionsPage/DataAppPermissionsPage.tsx b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppPermissionsPage/DataAppPermissionsPage.tsxnew file mode 100644index 00000000000..3f6e8183dba--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppPermissionsPage/DataAppPermissionsPage.tsx@@ -0,0 +1,79 @@+import { useDisclosure, useElementSize } from "@mantine/hooks";+import { useState } from "react";+import { t } from "ttag";++import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";+import { PageContainer } from "metabase/common/data-studio/components/PageContainer";+import { Button, Center, Flex, Stack } from "metabase/ui";+import { useGetDataAppGroupsQuery } from "metabase-enterprise/api";+import type { GroupId } from "metabase-types/api";++import { DataAppHeader } from "../../components/DataAppHeader";+import { useRouteDataApp } from "../../hooks/use-route-data-app";++import { AddDataAppGroupsModal } from "./AddDataAppGroupsModal";+import { DataAppGroupList } from "./DataAppGroupList";+import { DataAppGroupSidebar } from "./DataAppGroupSidebar";++export function DataAppPermissionsPage() {+ const { app, isLoading, error } = useRouteDataApp();+ const [isAdding, { open: openAdding, close: closeAdding }] =+ useDisclosure(false);+ const [isResizing, { open: startResizing, close: stopResizing }] =+ useDisclosure(false);+ const [selectedGroupId, setSelectedGroupId] = useState<GroupId>();+ const { ref: containerRef, width: containerWidth } = useElementSize();+ const { data: groups } = useGetDataAppGroupsQuery(app?.name ?? "", {+ skip: app == null,+ });+ const selectedGroup = groups?.find((group) => group.id === selectedGroupId);++ if (isLoading || error != null || app == null) {+ return (+ <Center h="100%">+ <LoadingAndErrorWrapper loading={isLoading} error={error} />+ </Center>+ );+ }++ return (+ <Flex+ ref={containerRef}+ h="100%"+ wrap="nowrap"+ style={isResizing ? { userSelect: "none" } : undefined}+ >+ <PageContainer+ data-testid="data-app-permissions"+ gap="lg"+ flex={1}+ miw={0}+ >+ <DataAppHeader app={app} />+ <Stack style={{ overflow: "hidden" }}>+ <Flex justify="flex-end">+ <Button variant="filled" onClick={openAdding}>+ {t`Add groups`}+ </Button>+ </Flex>+ <DataAppGroupList+ app={app}+ selectedGroupId={selectedGroup?.id}+ onSelectGroup={setSelectedGroupId}+ />+ </Stack>+ {isAdding && <AddDataAppGroupsModal app={app} onClose={closeAdding} />}+ </PageContainer>+ {selectedGroup != null && (+ <DataAppGroupSidebar+ app={app}+ group={selectedGroup}+ containerWidth={containerWidth}+ onResizeStart={startResizing}+ onResizeStop={stopResizing}+ onClose={() => setSelectedGroupId(undefined)}+ />+ )}+ </Flex>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppPermissionsPage/index.ts b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppPermissionsPage/index.tsnew file mode 100644index 00000000000..25d360d6f9d--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppPermissionsPage/index.ts@@ -0,0 +1 @@+export { DataAppPermissionsPage } from "./DataAppPermissionsPage";diff --git a/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppQuestionDependenciesPage/DataAppQuestionDependenciesPage.tsx b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppQuestionDependenciesPage/DataAppQuestionDependenciesPage.tsxnew file mode 100644index 00000000000..e1a8f1ac66d--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppQuestionDependenciesPage/DataAppQuestionDependenciesPage.tsx@@ -0,0 +1,40 @@+import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";+import { PageContainer } from "metabase/common/data-studio/components/PageContainer";+import { PLUGIN_DEPENDENCIES } from "metabase/plugins";+import { Outlet } from "metabase/router";+import { Card, Center } from "metabase/ui";+import * as Urls from "metabase/urls";++import { DataAppQuestionHeader } from "../../components/DataAppQuestionHeader";+import { useRouteDataAppQuestion } from "../../hooks/use-route-data-app-question";++export function DataAppQuestionDependenciesPage() {+ const { app, card, isLoading, error } = useRouteDataAppQuestion();++ if (isLoading || error != null || app == null || card == null) {+ return (+ <Center h="100%">+ <LoadingAndErrorWrapper loading={isLoading} error={error} />+ </Center>+ );+ }++ return (+ <PageContainer data-testid="data-app-question-dependencies">+ <DataAppQuestionHeader app={app} card={card} />+ <PLUGIN_DEPENDENCIES.DependencyGraphPageContext.Provider+ value={{+ baseUrl: Urls.dataStudioDataAppQuestionDependencies(+ app.name,+ card.id,+ ),+ defaultEntry: { id: card.id, type: "card" },+ }}+ >+ <Card p={0} withBorder flex={1}>+ <Outlet />+ </Card>+ </PLUGIN_DEPENDENCIES.DependencyGraphPageContext.Provider>+ </PageContainer>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppQuestionDependenciesPage/index.ts b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppQuestionDependenciesPage/index.tsnew file mode 100644index 00000000000..c3090381bb9--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppQuestionDependenciesPage/index.ts@@ -0,0 +1 @@+export { DataAppQuestionDependenciesPage } from "./DataAppQuestionDependenciesPage";diff --git a/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppQuestionPage/DataAppQuestionPage.tsx b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppQuestionPage/DataAppQuestionPage.tsxnew file mode 100644index 00000000000..0acc5e725e5--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppQuestionPage/DataAppQuestionPage.tsx@@ -0,0 +1,47 @@+import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";+import { AboutSidebar } from "metabase/common/data-studio/components/AboutSidebar";+import { AboutHeader } from "metabase/common/data-studio/components/AboutSidebar/AboutHeader";+import { CardDescription } from "metabase/common/data-studio/components/AboutSidebar/CardDescription";+import { CardSourceSubSection } from "metabase/common/data-studio/components/AboutSidebar/CardSourceSubSection";+import { OverviewVisualization } from "metabase/common/data-studio/components/OverviewVisualization";+import { PageContainer } from "metabase/common/data-studio/components/PageContainer";+import { Card, Center, Flex } from "metabase/ui";+import * as Urls from "metabase/urls";+import type { DatabaseId, TableId } from "metabase-types/api";++import { DataAppQuestionHeader } from "../../components/DataAppQuestionHeader";+import { useRouteDataAppQuestion } from "../../hooks/use-route-data-app-question";++const CARD_SOURCE_URLS = {+ database: (databaseId: DatabaseId) => Urls.dataStudioData({ databaseId }),+ table: (_databaseId: DatabaseId, tableId: TableId) =>+ Urls.dataStudioTable(tableId),+};++export function DataAppQuestionPage() {+ const { app, card, isLoading, error } = useRouteDataAppQuestion();++ if (isLoading || error != null || app == null || card == null) {+ return (+ <Center h="100%">+ <LoadingAndErrorWrapper loading={isLoading} error={error} />+ </Center>+ );+ }++ return (+ <PageContainer data-testid="data-app-question-overview">+ <DataAppQuestionHeader app={app} card={card} />+ <Flex flex={1} gap="lg" mih={0}>+ <Card withBorder p={0} flex={1} mah={700}>+ <OverviewVisualization card={card} />+ </Card>+ <AboutSidebar flex="0 0 360px">+ <AboutHeader updatedAt={card.updated_at} />+ <CardDescription card={card} />+ <CardSourceSubSection card={card} urls={CARD_SOURCE_URLS} mt="xxl" />+ </AboutSidebar>+ </Flex>+ </PageContainer>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppQuestionPage/index.ts b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppQuestionPage/index.tsnew file mode 100644index 00000000000..35ebadda0b2--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppQuestionPage/index.ts@@ -0,0 +1 @@+export { DataAppQuestionPage } from "./DataAppQuestionPage";diff --git a/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppQuestionsPage/DataAppQuestionsPage.tsx b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppQuestionsPage/DataAppQuestionsPage.tsxnew file mode 100644index 00000000000..b29b430b275--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppQuestionsPage/DataAppQuestionsPage.tsx@@ -0,0 +1,36 @@+import { t } from "ttag";++import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";+import { PageContainer } from "metabase/common/data-studio/components/PageContainer";+import { Center } from "metabase/ui";+import * as Urls from "metabase/urls";++import { DataAppHeader } from "../../components/DataAppHeader";+import { DataAppItemList } from "../../components/DataAppItemList";+import { useRouteDataApp } from "../../hooks/use-route-data-app";++export function DataAppQuestionsPage() {+ const { app, isLoading, error } = useRouteDataApp();++ if (isLoading || error != null || app == null) {+ return (+ <Center h="100%">+ <LoadingAndErrorWrapper loading={isLoading} error={error} />+ </Center>+ );+ }++ return (+ <PageContainer data-testid="data-app-questions" gap="lg">+ <DataAppHeader app={app} />+ <DataAppItemList+ app={app}+ model="card"+ emptyMessage={t`No questions yet`}+ getItemUrl={(cardId) =>+ Urls.dataStudioDataAppQuestion(app.name, cardId)+ }+ />+ </PageContainer>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppQuestionsPage/index.ts b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppQuestionsPage/index.tsnew file mode 100644index 00000000000..bfd479f03bc--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppQuestionsPage/index.ts@@ -0,0 +1 @@+export { DataAppQuestionsPage } from "./DataAppQuestionsPage";diff --git a/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppsSectionLayout/DataAppsSectionLayout.tsx b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppsSectionLayout/DataAppsSectionLayout.tsxnew file mode 100644index 00000000000..396a9ba31d5--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppsSectionLayout/DataAppsSectionLayout.tsx@@ -0,0 +1,10 @@+import { t } from "ttag";++import { usePageTitle } from "metabase/hooks/use-page-title";+import { Outlet } from "metabase/router";++export function DataAppsSectionLayout() {+ usePageTitle(t`Data apps`);++ return <Outlet />;+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppsSectionLayout/index.ts b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppsSectionLayout/index.tsnew file mode 100644index 00000000000..3a0d8379045--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppsSectionLayout/index.ts@@ -0,0 +1 @@+export { DataAppsSectionLayout } from "./DataAppsSectionLayout";diff --git a/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/routes.tsx b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/routes.tsxnew file mode 100644index 00000000000..7ebc4aa6d46--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/routes.tsx@@ -0,0 +1,113 @@+import type { ComponentType } from "react";++import { PLUGIN_DEPENDENCIES } from "metabase/plugins";+import { Route } from "metabase/router";+import * as Urls from "metabase/urls";++const sectionLayout = () =>+ import(+ /* webpackChunkName: "data-studio-data-apps" */ "./pages/DataAppsSectionLayout"+ ).then(({ DataAppsSectionLayout }) => ({ Component: DataAppsSectionLayout }));++const listPage = () =>+ import(+ /* webpackChunkName: "data-studio-data-apps" */ "./pages/DataAppListPage"+ ).then(({ DataAppListPage }) => ({ Component: DataAppListPage }));++const overviewPage = () =>+ import(+ /* webpackChunkName: "data-studio-data-apps" */ "./pages/DataAppOverviewPage"+ ).then(({ DataAppOverviewPage }) => ({ Component: DataAppOverviewPage }));++const questionsPage = () =>+ import(+ /* webpackChunkName: "data-studio-data-apps" */ "./pages/DataAppQuestionsPage"+ ).then(({ DataAppQuestionsPage }) => ({ Component: DataAppQuestionsPage }));++const actionsPage = () =>+ import(+ /* webpackChunkName: "data-studio-data-apps" */ "./pages/DataAppActionsPage"+ ).then(({ DataAppActionsPage }) => ({ Component: DataAppActionsPage }));++const questionPage = () =>+ import(+ /* webpackChunkName: "data-studio-data-apps" */ "./pages/DataAppQuestionPage"+ ).then(({ DataAppQuestionPage }) => ({ Component: DataAppQuestionPage }));++const questionDependenciesPage = () =>+ import(+ /* webpackChunkName: "data-studio-data-apps" */ "./pages/DataAppQuestionDependenciesPage"+ ).then(({ DataAppQuestionDependenciesPage }) => ({+ Component: DataAppQuestionDependenciesPage,+ }));++const permissionsPage = () =>+ import(+ /* webpackChunkName: "data-studio-data-apps" */ "./pages/DataAppPermissionsPage"+ ).then(({ DataAppPermissionsPage }) => ({+ Component: DataAppPermissionsPage,+ }));++const actionDefinitionPage = () =>+ import(+ /* webpackChunkName: "data-studio-data-apps" */ "./pages/DataAppActionDefinitionPage"+ ).then(({ DataAppActionDefinitionPage }) => ({+ Component: DataAppActionDefinitionPage,+ }));++const actionFieldsPage = () =>+ import(+ /* webpackChunkName: "data-studio-data-apps" */ "./pages/DataAppActionFieldsPage"+ ).then(({ DataAppActionFieldsPage }) => ({+ Component: DataAppActionFieldsPage,+ }));++const actionDependenciesPage = () =>+ import(+ /* webpackChunkName: "data-studio-data-apps" */ "./pages/DataAppActionDependenciesPage"+ ).then(({ DataAppActionDependenciesPage }) => ({+ Component: DataAppActionDependenciesPage,+ }));++export function getDataStudioDataAppRoutes(IsAdmin: ComponentType) {+ return (+ <Route path={Urls.DATA_APP_URL_SEGMENT} element={<IsAdmin />}>+ <Route lazy={sectionLayout}>+ <Route index lazy={listPage} />+ <Route path=":name" lazy={overviewPage} />+ <Route path=":name/questions" lazy={questionsPage} />+ <Route path=":name/actions" lazy={actionsPage} />+ <Route path=":name/permissions" lazy={permissionsPage} />+ <Route path=":name/questions/:cardId" lazy={questionPage} />+ {PLUGIN_DEPENDENCIES.isEnabled && (+ <Route+ path=":name/questions/:cardId/dependencies"+ lazy={questionDependenciesPage}+ >+ <Route+ index+ element={<PLUGIN_DEPENDENCIES.DependencyGraphPage />}+ />+ </Route>+ )}+ <Route path=":name/actions/:actionId" lazy={actionDefinitionPage} />+ <Route path=":name/actions/:actionId/fields" lazy={actionFieldsPage} />+ <Route+ path=":name/actions/:actionId/fields/:fieldId"+ lazy={actionFieldsPage}+ />+ {PLUGIN_DEPENDENCIES.isEnabled && (+ <Route+ path=":name/actions/:actionId/dependencies"+ lazy={actionDependenciesPage}+ >+ <Route+ index+ element={<PLUGIN_DEPENDENCIES.DependencyGraphPage />}+ />+ </Route>+ )}+ </Route>+ </Route>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/utils.ts b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/utils.tsnew file mode 100644index 00000000000..3e408fa3785--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/utils.ts@@ -0,0 +1,16 @@+import { t } from "ttag";++import type { DataApp } from "metabase-types/api";++type DataAppState = Pick<DataApp, "enabled" | "outdated">;++export function getDataAppStatusLabel({ enabled, outdated }: DataAppState) {+ if (enabled) {+ return outdated ? t`Live, outdated` : t`Live`;+ }+ return outdated ? t`Draft, outdated` : t`Draft`;+}++export function isDataAppOpenable({ enabled, outdated }: DataAppState) {+ return enabled && !outdated;+}diff --git a/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/utils.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/utils.unit.spec.tsnew file mode 100644index 00000000000..f46e39ef04e--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/utils.unit.spec.ts@@ -0,0 +1,28 @@+import { getDataAppStatusLabel, isDataAppOpenable } from "./utils";++describe("getDataAppStatusLabel", () => {+ it.each([+ { enabled: true, outdated: false, label: "Live" },+ { enabled: false, outdated: false, label: "Draft" },+ { enabled: true, outdated: true, label: "Live, outdated" },+ { enabled: false, outdated: true, label: "Draft, outdated" },+ ])(+ "returns $label when enabled is $enabled and outdated is $outdated",+ ({ enabled, outdated, label }) => {+ expect(getDataAppStatusLabel({ enabled, outdated })).toBe(label);+ },+ );+});++describe("isDataAppOpenable", () => {+ it.each([+ { enabled: true, outdated: false, isOpenable: true },+ { enabled: false, outdated: false, isOpenable: false },+ { enabled: true, outdated: true, isOpenable: false },+ ])(+ "returns $isOpenable when enabled is $enabled and outdated is $outdated",+ ({ enabled, outdated, isOpenable }) => {+ expect(isDataAppOpenable({ enabled, outdated })).toBe(isOpenable);+ },+ );+});diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/components/DataAppLayout/DataAppLayout.module.css b/enterprise/frontend/src/metabase-enterprise/data-apps/host/components/DataAppLayout/DataAppLayout.module.csssimilarity index 100%rename from enterprise/frontend/src/metabase-enterprise/data_apps/components/DataAppLayout/DataAppLayout.module.cssrename to enterprise/frontend/src/metabase-enterprise/data-apps/host/components/DataAppLayout/DataAppLayout.module.cssdiff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/components/DataAppLayout/DataAppLayout.tsx b/enterprise/frontend/src/metabase-enterprise/data-apps/host/components/DataAppLayout/DataAppLayout.tsxsimilarity index 100%rename from enterprise/frontend/src/metabase-enterprise/data_apps/components/DataAppLayout/DataAppLayout.tsxrename to enterprise/frontend/src/metabase-enterprise/data-apps/host/components/DataAppLayout/DataAppLayout.tsxdiff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/components/DataAppLayout/DataAppLayout.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data-apps/host/components/DataAppLayout/DataAppLayout.unit.spec.tsxsimilarity index 100%rename from enterprise/frontend/src/metabase-enterprise/data_apps/components/DataAppLayout/DataAppLayout.unit.spec.tsxrename to enterprise/frontend/src/metabase-enterprise/data-apps/host/components/DataAppLayout/DataAppLayout.unit.spec.tsxdiff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/components/DataAppView/DataAppView.module.css b/enterprise/frontend/src/metabase-enterprise/data-apps/host/components/DataAppView/DataAppView.module.csssimilarity index 100%rename from enterprise/frontend/src/metabase-enterprise/data_apps/components/DataAppView/DataAppView.module.cssrename to enterprise/frontend/src/metabase-enterprise/data-apps/host/components/DataAppView/DataAppView.module.cssdiff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/components/DataAppView/DataAppView.tsx b/enterprise/frontend/src/metabase-enterprise/data-apps/host/components/DataAppView/DataAppView.tsxsimilarity index 94%rename from enterprise/frontend/src/metabase-enterprise/data_apps/components/DataAppView/DataAppView.tsxrename to enterprise/frontend/src/metabase-enterprise/data-apps/host/components/DataAppView/DataAppView.tsxindex d5913d82ed5..131116e373f 100644--- a/enterprise/frontend/src/metabase-enterprise/data_apps/components/DataAppView/DataAppView.tsx+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/host/components/DataAppView/DataAppView.tsx@@ -28,7 +28,7 @@ import {DATA_APP_READY_MESSAGE_TYPE,type DataAppBundleErrorMessage,getOutdatedDataAppMessage,-} from "../../constants";+} from "../../../constants";import { attachIframeUrlMirror } from "../../lib/attach-iframe-url-mirror";import { deriveIframeSrc } from "../../lib/derive-iframe-src";import { isCrossOriginError } from "../../lib/is-cross-origin-error";@@ -67,8 +67,19 @@ const CenteredEmptyState = ({* The data-app bundle itself knows nothing about either direction —* it just uses React Router as if it were the top-level app.*/-export function DataAppView() {- const { name = "" } = useParams<{ name: string }>();+type DataAppViewProps = {+ name?: string;+ enableUrlMirroring?: boolean;+ enableDrafts?: boolean;+};++export function DataAppView({+ name: nameProp,+ enableUrlMirroring = false,+ enableDrafts = false,+}: DataAppViewProps = {}) {+ const { name: nameParam = "" } = useParams<{ name: string }>();+ const name = nameProp ?? nameParam;const validName = name.length > 0;const iframeRef = useRef<HTMLIFrameElement | null>(null);@@ -108,7 +119,7 @@ export function DataAppView() {} = useGetDataAppQuery(name, { skip: !validName });useEffect(() => {- if (!iframeEl || !validName) {+ if (!iframeEl || !validName || !enableUrlMirroring) {return undefined;}@@ -149,7 +160,7 @@ export function DataAppView() {iframeEl.removeEventListener("load", onLoad);detach?.();};- }, [iframeEl, name, validName]);+ }, [iframeEl, name, validName, enableUrlMirroring]);useEffect(() => {const onMessage = (event: MessageEvent) => {@@ -237,6 +248,15 @@ export function DataAppView() {return <LoadingAndErrorWrapper loading />;}+ if (meta?.enabled === false && !enableDrafts) {+ return (+ <NotFound+ title={t`Data app not found`}+ message={t`This data app doesn’t exist or has been disabled.`}+ />+ );+ }+if (metaError || !meta) {// A disabled or non-existent app 404s from the metadata endpoint; anything// else is an unexpected failure.diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/components/DataAppView/DataAppView.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data-apps/host/components/DataAppView/DataAppView.unit.spec.tsxsimilarity index 93%rename from enterprise/frontend/src/metabase-enterprise/data_apps/components/DataAppView/DataAppView.unit.spec.tsxrename to enterprise/frontend/src/metabase-enterprise/data-apps/host/components/DataAppView/DataAppView.unit.spec.tsxindex 4fa11f132d1..aa09d5111c8 100644--- a/enterprise/frontend/src/metabase-enterprise/data_apps/components/DataAppView/DataAppView.unit.spec.tsx+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/host/components/DataAppView/DataAppView.unit.spec.tsx@@ -9,7 +9,7 @@ import {DATA_APP_ERROR_MESSAGE_TYPE,DATA_APP_LOAD_TIMEOUT_MS,DATA_APP_READY_MESSAGE_TYPE,-} from "../../constants";+} from "../../../constants";import { DataAppView } from "./DataAppView";@@ -25,6 +25,7 @@ type SetupOpts = {data?: ReturnType<typeof createMockDataApp>;isLoading?: boolean;error?: unknown;+ enableDrafts?: boolean;};function setup({@@ -32,6 +33,7 @@ function setup({data,isLoading = false,error,+ enableDrafts,}: SetupOpts = {}) {// RTK Query's hook result is a wide discriminated union (refetch, status,// isFetching, …); the component reads only these three fields.@@ -44,8 +46,11 @@ function setup({renderWithProviders(<>{/* The empty-name case has no `:name` segment to match. */}- <Route path="/" element={<DataAppView />} />- <Route path=":name" element={<DataAppView />} />+ <Route path="/" element={<DataAppView enableDrafts={enableDrafts} />} />+ <Route+ path=":name"+ element={<DataAppView enableDrafts={enableDrafts} />}+ /></>,{ withRouter: true, initialRoute: `/${name}` },);@@ -66,6 +71,18 @@ describe("DataAppView", () => {expect(screen.getByText("Data app not found")).toBeInTheDocument();});+ it("shows a not-found screen when an admin opens a disabled app", () => {+ setup({ data: createMockDataApp({ enabled: false }) });++ expect(screen.getByText("Data app not found")).toBeInTheDocument();+ });++ it("shows a disabled app when drafts are allowed", () => {+ setup({ data: createMockDataApp({ enabled: false }), enableDrafts: true });++ expect(screen.queryByText("Data app not found")).not.toBeInTheDocument();+ });+it("shows a generic error screen for an unexpected failure", async () => {setup({ error: { status: 500 } });diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/lib/attach-iframe-url-mirror.ts b/enterprise/frontend/src/metabase-enterprise/data-apps/host/lib/attach-iframe-url-mirror.tssimilarity index 100%rename from enterprise/frontend/src/metabase-enterprise/data_apps/lib/attach-iframe-url-mirror.tsrename to enterprise/frontend/src/metabase-enterprise/data-apps/host/lib/attach-iframe-url-mirror.tsdiff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/lib/attach-iframe-url-mirror.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/data-apps/host/lib/attach-iframe-url-mirror.unit.spec.tssimilarity index 100%rename from enterprise/frontend/src/metabase-enterprise/data_apps/lib/attach-iframe-url-mirror.unit.spec.tsrename to enterprise/frontend/src/metabase-enterprise/data-apps/host/lib/attach-iframe-url-mirror.unit.spec.tsdiff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/lib/derive-iframe-src.ts b/enterprise/frontend/src/metabase-enterprise/data-apps/host/lib/derive-iframe-src.tssimilarity index 100%rename from enterprise/frontend/src/metabase-enterprise/data_apps/lib/derive-iframe-src.tsrename to enterprise/frontend/src/metabase-enterprise/data-apps/host/lib/derive-iframe-src.tsdiff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/lib/derive-iframe-src.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/data-apps/host/lib/derive-iframe-src.unit.spec.tssimilarity index 100%rename from enterprise/frontend/src/metabase-enterprise/data_apps/lib/derive-iframe-src.unit.spec.tsrename to enterprise/frontend/src/metabase-enterprise/data-apps/host/lib/derive-iframe-src.unit.spec.tsdiff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/lib/is-cross-origin-error.ts b/enterprise/frontend/src/metabase-enterprise/data-apps/host/lib/is-cross-origin-error.tssimilarity index 100%rename from enterprise/frontend/src/metabase-enterprise/data_apps/lib/is-cross-origin-error.tsrename to enterprise/frontend/src/metabase-enterprise/data-apps/host/lib/is-cross-origin-error.tsdiff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/lib/is-data-app-message.ts b/enterprise/frontend/src/metabase-enterprise/data-apps/host/lib/is-data-app-message.tssimilarity index 100%rename from enterprise/frontend/src/metabase-enterprise/data_apps/lib/is-data-app-message.tsrename to enterprise/frontend/src/metabase-enterprise/data-apps/host/lib/is-data-app-message.tsdiff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/lib/is-data-app-message.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/data-apps/host/lib/is-data-app-message.unit.spec.tssimilarity index 97%rename from enterprise/frontend/src/metabase-enterprise/data_apps/lib/is-data-app-message.unit.spec.tsrename to enterprise/frontend/src/metabase-enterprise/data-apps/host/lib/is-data-app-message.unit.spec.tsindex f3054c1c76b..174d43a9f33 100644--- a/enterprise/frontend/src/metabase-enterprise/data_apps/lib/is-data-app-message.unit.spec.ts+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/host/lib/is-data-app-message.unit.spec.ts@@ -1,7 +1,7 @@import {DATA_APP_ERROR_MESSAGE_TYPE,DATA_APP_READY_MESSAGE_TYPE,-} from "../constants";+} from "../../constants";import { isDataAppMessage } from "./is-data-app-message";diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/routes.tsx b/enterprise/frontend/src/metabase-enterprise/data-apps/host/routes.tsxsimilarity index 94%rename from enterprise/frontend/src/metabase-enterprise/data_apps/routes.tsxrename to enterprise/frontend/src/metabase-enterprise/data-apps/host/routes.tsxindex 83a3d877ad6..3f6ea77b54f 100644--- a/enterprise/frontend/src/metabase-enterprise/data_apps/routes.tsx+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/host/routes.tsx@@ -18,7 +18,9 @@ const dataAppView = () =>import(/* webpackChunkName: "data-apps" */ "./components/DataAppView/DataAppView").then(({ DataAppView }) => ({- Component: DataAppView,+ Component: function DataAppViewRoute() {+ return <DataAppView enableUrlMirroring />;+ },}));/**diff --git a/enterprise/frontend/src/metabase-enterprise/data-apps/index.tsx b/enterprise/frontend/src/metabase-enterprise/data-apps/index.tsxnew file mode 100644index 00000000000..e2124a0b9e9--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/index.tsx@@ -0,0 +1,19 @@+import { PLUGIN_DATA_APPS } from "metabase/plugins";+import { hasPremiumFeature } from "metabase-enterprise/settings";++import { getDataStudioDataAppRoutes } from "./data-studio/routes";+import { getRoutes, registerDataAppsPagePrefetch } from "./host/routes";+import { DataAppsNavbarSection } from "./navbar/DataAppsNavbarSection";++/**+ * Initialize data-apps plugin features, gated on the `data-apps` token feature.+ */+export function initializePlugin() {+ if (hasPremiumFeature("data-apps")) {+ PLUGIN_DATA_APPS.isEnabled = true;+ PLUGIN_DATA_APPS.getRoutes = getRoutes;+ PLUGIN_DATA_APPS.getDataStudioRoutes = getDataStudioDataAppRoutes;+ PLUGIN_DATA_APPS.MainNavbarSection = DataAppsNavbarSection;+ registerDataAppsPagePrefetch();+ }+}diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/navbar/DataAppsNavbarSection.tsx b/enterprise/frontend/src/metabase-enterprise/data-apps/navbar/DataAppsNavbarSection.tsxsimilarity index 100%rename from enterprise/frontend/src/metabase-enterprise/data_apps/navbar/DataAppsNavbarSection.tsxrename to enterprise/frontend/src/metabase-enterprise/data-apps/navbar/DataAppsNavbarSection.tsxdiff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/navbar/DataAppsNavbarSection.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data-apps/navbar/DataAppsNavbarSection.unit.spec.tsxsimilarity index 100%rename from enterprise/frontend/src/metabase-enterprise/data_apps/navbar/DataAppsNavbarSection.unit.spec.tsxrename to enterprise/frontend/src/metabase-enterprise/data-apps/navbar/DataAppsNavbarSection.unit.spec.tsxdiff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/app-data-app.tsx b/enterprise/frontend/src/metabase-enterprise/data-apps/runtime/app-data-app.tsxsimilarity index 100%rename from enterprise/frontend/src/metabase-enterprise/data_apps/runtime/app-data-app.tsxrename to enterprise/frontend/src/metabase-enterprise/data-apps/runtime/app-data-app.tsxdiff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/components/DataAppErrorState/DataAppErrorState.tsx b/enterprise/frontend/src/metabase-enterprise/data-apps/runtime/components/DataAppErrorState/DataAppErrorState.tsxsimilarity index 100%rename from enterprise/frontend/src/metabase-enterprise/data_apps/runtime/components/DataAppErrorState/DataAppErrorState.tsxrename to enterprise/frontend/src/metabase-enterprise/data-apps/runtime/components/DataAppErrorState/DataAppErrorState.tsxdiff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/components/DataAppIframeApp/DataAppIframeApp.tsx b/enterprise/frontend/src/metabase-enterprise/data-apps/runtime/components/DataAppIframeApp/DataAppIframeApp.tsxsimilarity index 100%rename from enterprise/frontend/src/metabase-enterprise/data_apps/runtime/components/DataAppIframeApp/DataAppIframeApp.tsxrename to enterprise/frontend/src/metabase-enterprise/data-apps/runtime/components/DataAppIframeApp/DataAppIframeApp.tsxdiff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/components/DataAppIframeApp/DataAppIframeApp.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data-apps/runtime/components/DataAppIframeApp/DataAppIframeApp.unit.spec.tsxsimilarity index 100%rename from enterprise/frontend/src/metabase-enterprise/data_apps/runtime/components/DataAppIframeApp/DataAppIframeApp.unit.spec.tsxrename to enterprise/frontend/src/metabase-enterprise/data-apps/runtime/components/DataAppIframeApp/DataAppIframeApp.unit.spec.tsxdiff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/components/DataAppProvider/DataAppProvider.tsx b/enterprise/frontend/src/metabase-enterprise/data-apps/runtime/components/DataAppProvider/DataAppProvider.tsxsimilarity index 98%rename from enterprise/frontend/src/metabase-enterprise/data_apps/runtime/components/DataAppProvider/DataAppProvider.tsxrename to enterprise/frontend/src/metabase-enterprise/data-apps/runtime/components/DataAppProvider/DataAppProvider.tsxindex 7904e9aa389..cc115e3ad77 100644--- a/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/components/DataAppProvider/DataAppProvider.tsx+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/runtime/components/DataAppProvider/DataAppProvider.tsx@@ -8,7 +8,7 @@ import { SdkThemeProvider } from "embedding-sdk-bundle/components/private/SdkTheimport { setDataApp } from "metabase/embedding/config";import { MetabaseReduxProvider } from "metabase/redux";import { getCspNonce } from "metabase/utils/csp";-import type { DataAppMetabaseProviderProps } from "metabase-enterprise/data_apps/sandbox/types";+import type { DataAppMetabaseProviderProps } from "metabase-enterprise/data-apps/sandbox/types";import { useHostSdkStore } from "../../lib/use-host-sdk-store";import { DataAppErrorState } from "../DataAppErrorState/DataAppErrorState";diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/components/DataAppProvider/DataAppProvider.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data-apps/runtime/components/DataAppProvider/DataAppProvider.unit.spec.tsxsimilarity index 100%rename from enterprise/frontend/src/metabase-enterprise/data_apps/runtime/components/DataAppProvider/DataAppProvider.unit.spec.tsxrename to enterprise/frontend/src/metabase-enterprise/data-apps/runtime/components/DataAppProvider/DataAppProvider.unit.spec.tsxdiff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/iframe-vendors.ts b/enterprise/frontend/src/metabase-enterprise/data-apps/runtime/iframe-vendors.tssimilarity index 63%rename from enterprise/frontend/src/metabase-enterprise/data_apps/runtime/iframe-vendors.tsrename to enterprise/frontend/src/metabase-enterprise/data-apps/runtime/iframe-vendors.tsindex f2bbe7641d9..9bbdda5bd93 100644--- a/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/iframe-vendors.ts+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/runtime/iframe-vendors.ts@@ -1,4 +1,4 @@import "@mantine/core/styles.css";import "@mantine/dates/styles.css";-import "metabase-enterprise/data_apps/sandbox/iframe-baseline.css";+import "metabase-enterprise/data-apps/sandbox/iframe-baseline.css";import "metabase/utils/csp-setup";diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/lib/describe-error.ts b/enterprise/frontend/src/metabase-enterprise/data-apps/runtime/lib/describe-error.tssimilarity index 100%rename from enterprise/frontend/src/metabase-enterprise/data_apps/runtime/lib/describe-error.tsrename to enterprise/frontend/src/metabase-enterprise/data-apps/runtime/lib/describe-error.tsdiff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/lib/describe-error.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/data-apps/runtime/lib/describe-error.unit.spec.tssimilarity index 100%rename from enterprise/frontend/src/metabase-enterprise/data_apps/runtime/lib/describe-error.unit.spec.tsrename to enterprise/frontend/src/metabase-enterprise/data-apps/runtime/lib/describe-error.unit.spec.tsdiff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/lib/read-name-from-url.ts b/enterprise/frontend/src/metabase-enterprise/data-apps/runtime/lib/read-name-from-url.tssimilarity index 100%rename from enterprise/frontend/src/metabase-enterprise/data_apps/runtime/lib/read-name-from-url.tsrename to enterprise/frontend/src/metabase-enterprise/data-apps/runtime/lib/read-name-from-url.tsdiff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/lib/read-name-from-url.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/data-apps/runtime/lib/read-name-from-url.unit.spec.tssimilarity index 100%rename from enterprise/frontend/src/metabase-enterprise/data_apps/runtime/lib/read-name-from-url.unit.spec.tsrename to enterprise/frontend/src/metabase-enterprise/data-apps/runtime/lib/read-name-from-url.unit.spec.tsdiff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/lib/report-error-to-parent.ts b/enterprise/frontend/src/metabase-enterprise/data-apps/runtime/lib/report-error-to-parent.tssimilarity index 100%rename from enterprise/frontend/src/metabase-enterprise/data_apps/runtime/lib/report-error-to-parent.tsrename to enterprise/frontend/src/metabase-enterprise/data-apps/runtime/lib/report-error-to-parent.tsdiff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/lib/report-ready-to-parent.ts b/enterprise/frontend/src/metabase-enterprise/data-apps/runtime/lib/report-ready-to-parent.tssimilarity index 100%rename from enterprise/frontend/src/metabase-enterprise/data_apps/runtime/lib/report-ready-to-parent.tsrename to enterprise/frontend/src/metabase-enterprise/data-apps/runtime/lib/report-ready-to-parent.tsdiff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/lib/use-data-app-bundle.ts b/enterprise/frontend/src/metabase-enterprise/data-apps/runtime/lib/use-data-app-bundle.tssimilarity index 98%rename from enterprise/frontend/src/metabase-enterprise/data_apps/runtime/lib/use-data-app-bundle.tsrename to enterprise/frontend/src/metabase-enterprise/data-apps/runtime/lib/use-data-app-bundle.tsindex 7cea5e4df37..5dc4428e673 100644--- a/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/lib/use-data-app-bundle.ts+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/runtime/lib/use-data-app-bundle.ts@@ -1,6 +1,6 @@import { type ComponentType, useEffect, useState } from "react";-import type { DataAppMetabaseProviderProps } from "metabase-enterprise/data_apps/sandbox/types";+import type { DataAppMetabaseProviderProps } from "metabase-enterprise/data-apps/sandbox/types";import {DataAppBundleError,diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/lib/use-data-app-bundle.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/data-apps/runtime/lib/use-data-app-bundle.unit.spec.tssimilarity index 100%rename from enterprise/frontend/src/metabase-enterprise/data_apps/runtime/lib/use-data-app-bundle.unit.spec.tsrename to enterprise/frontend/src/metabase-enterprise/data-apps/runtime/lib/use-data-app-bundle.unit.spec.tsdiff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/lib/use-host-sdk-store-auth.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data-apps/runtime/lib/use-host-sdk-store-auth.unit.spec.tsxsimilarity index 100%rename from enterprise/frontend/src/metabase-enterprise/data_apps/runtime/lib/use-host-sdk-store-auth.unit.spec.tsxrename to enterprise/frontend/src/metabase-enterprise/data-apps/runtime/lib/use-host-sdk-store-auth.unit.spec.tsxdiff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/lib/use-host-sdk-store.ts b/enterprise/frontend/src/metabase-enterprise/data-apps/runtime/lib/use-host-sdk-store.tssimilarity index 100%rename from enterprise/frontend/src/metabase-enterprise/data_apps/runtime/lib/use-host-sdk-store.tsrename to enterprise/frontend/src/metabase-enterprise/data-apps/runtime/lib/use-host-sdk-store.tsdiff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/lib/use-host-sdk-store.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/data-apps/runtime/lib/use-host-sdk-store.unit.spec.tssimilarity index 100%rename from enterprise/frontend/src/metabase-enterprise/data_apps/runtime/lib/use-host-sdk-store.unit.spec.tsrename to enterprise/frontend/src/metabase-enterprise/data-apps/runtime/lib/use-host-sdk-store.unit.spec.tsdiff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/loader.ts b/enterprise/frontend/src/metabase-enterprise/data-apps/runtime/loader.tssimilarity index 97%rename from enterprise/frontend/src/metabase-enterprise/data_apps/runtime/loader.tsrename to enterprise/frontend/src/metabase-enterprise/data-apps/runtime/loader.tsindex 650beb7acea..b0e40096071 100644--- a/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/loader.ts+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/runtime/loader.ts@@ -8,11 +8,11 @@ import { pick } from "underscore";import * as sdkExports from "embedding-sdk-package";import * as dataAppExports from "embedding-sdk-package/data-app";import { DATA_APP_REALM_HOST_URL, getSubpathSafeUrl } from "metabase/urls";-import { createDataAppSandbox } from "metabase-enterprise/data_apps/sandbox/sandbox";+import { createDataAppSandbox } from "metabase-enterprise/data-apps/sandbox/sandbox";import {DATA_APP_PROVIDER_PROP_KEYS,type DataAppMetabaseProviderProps,-} from "metabase-enterprise/data_apps/sandbox/types";+} from "metabase-enterprise/data-apps/sandbox/types";export interface LoadedDataApp {component: React.ComponentType<Record<string, unknown>>;diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/loader.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/data-apps/runtime/loader.unit.spec.tssimilarity index 96%rename from enterprise/frontend/src/metabase-enterprise/data_apps/runtime/loader.unit.spec.tsrename to enterprise/frontend/src/metabase-enterprise/data-apps/runtime/loader.unit.spec.tsindex b1c7d6b9e89..6f9e95d6dea 100644--- a/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/loader.unit.spec.ts+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/runtime/loader.unit.spec.ts@@ -1,4 +1,4 @@-import { createDataAppSandbox } from "metabase-enterprise/data_apps/sandbox/sandbox";+import { createDataAppSandbox } from "metabase-enterprise/data-apps/sandbox/sandbox";import {DataAppBundleError,@@ -6,8 +6,8 @@ import {instantiateDataAppBundle,} from "./loader";-jest.mock("metabase-enterprise/data_apps/sandbox/sandbox", () => ({- ...jest.requireActual("metabase-enterprise/data_apps/sandbox/sandbox"),+jest.mock("metabase-enterprise/data-apps/sandbox/sandbox", () => ({+ ...jest.requireActual("metabase-enterprise/data-apps/sandbox/sandbox"),createDataAppSandbox: jest.fn(),}));diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/allowed-hosts.ts b/enterprise/frontend/src/metabase-enterprise/data-apps/sandbox/allowed-hosts.tssimilarity index 100%rename from enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/allowed-hosts.tsrename to enterprise/frontend/src/metabase-enterprise/data-apps/sandbox/allowed-hosts.tsdiff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/allowed-hosts.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/data-apps/sandbox/allowed-hosts.unit.spec.tssimilarity index 100%rename from enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/allowed-hosts.unit.spec.tsrename to enterprise/frontend/src/metabase-enterprise/data-apps/sandbox/allowed-hosts.unit.spec.tsdiff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/create-element.ts b/enterprise/frontend/src/metabase-enterprise/data-apps/sandbox/create-element.tssimilarity index 100%rename from enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/create-element.tsrename to enterprise/frontend/src/metabase-enterprise/data-apps/sandbox/create-element.tsdiff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/create-element.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/data-apps/sandbox/create-element.unit.spec.tssimilarity index 100%rename from enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/create-element.unit.spec.tsrename to enterprise/frontend/src/metabase-enterprise/data-apps/sandbox/create-element.unit.spec.tsdiff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/distortions.ts b/enterprise/frontend/src/metabase-enterprise/data-apps/sandbox/distortions.tssimilarity index 100%rename from enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/distortions.tsrename to enterprise/frontend/src/metabase-enterprise/data-apps/sandbox/distortions.tsdiff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/distortions.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/data-apps/sandbox/distortions.unit.spec.tssimilarity index 100%rename from enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/distortions.unit.spec.tsrename to enterprise/frontend/src/metabase-enterprise/data-apps/sandbox/distortions.unit.spec.tsdiff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/globals.ts b/enterprise/frontend/src/metabase-enterprise/data-apps/sandbox/globals.tssimilarity index 100%rename from enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/globals.tsrename to enterprise/frontend/src/metabase-enterprise/data-apps/sandbox/globals.tsdiff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/host-element-guard.ts b/enterprise/frontend/src/metabase-enterprise/data-apps/sandbox/host-element-guard.tssimilarity index 100%rename from enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/host-element-guard.tsrename to enterprise/frontend/src/metabase-enterprise/data-apps/sandbox/host-element-guard.tsdiff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/host-element-guard.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/data-apps/sandbox/host-element-guard.unit.spec.tssimilarity index 100%rename from enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/host-element-guard.unit.spec.tsrename to enterprise/frontend/src/metabase-enterprise/data-apps/sandbox/host-element-guard.unit.spec.tsdiff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/iframe-baseline.css b/enterprise/frontend/src/metabase-enterprise/data-apps/sandbox/iframe-baseline.csssimilarity index 100%rename from enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/iframe-baseline.cssrename to enterprise/frontend/src/metabase-enterprise/data-apps/sandbox/iframe-baseline.cssdiff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/sandbox.ts b/enterprise/frontend/src/metabase-enterprise/data-apps/sandbox/sandbox.tssimilarity index 100%rename from enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/sandbox.tsrename to enterprise/frontend/src/metabase-enterprise/data-apps/sandbox/sandbox.tsdiff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/sandbox.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/data-apps/sandbox/sandbox.unit.spec.tssimilarity index 100%rename from enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/sandbox.unit.spec.tsrename to enterprise/frontend/src/metabase-enterprise/data-apps/sandbox/sandbox.unit.spec.tsdiff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/types.ts b/enterprise/frontend/src/metabase-enterprise/data-apps/sandbox/types.tssimilarity index 100%rename from enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/types.tsrename to enterprise/frontend/src/metabase-enterprise/data-apps/sandbox/types.tsdiff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/components/LibraryEmptyState/LibraryEmptyState.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/components/LibraryEmptyState/LibraryEmptyState.tsxindex 574058f3c79..3ebbdb1006f 100644--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/components/LibraryEmptyState/LibraryEmptyState.tsx+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/components/LibraryEmptyState/LibraryEmptyState.tsx@@ -3,20 +3,10 @@ import { t } from "ttag";import { getErrorMessage } from "metabase/api/utils";import { trackDataStudioLibraryCreated } from "metabase/common/data-studio/analytics";+import { FeatureEmptyState } from "metabase/common/data-studio/components/FeatureEmptyState";import { useMetadataToasts } from "metabase/common/hooks";-import {- Button,- Card,- Group,- Icon,- Paper,- SimpleGrid,- Stack,- Text,- Title,-} from "metabase/ui";+import { Button, Group, Stack, Text } from "metabase/ui";import { useCreateLibraryMutation } from "metabase-enterprise/api";-import type { IconName } from "metabase-types/api";export function LibraryEmptyState() {const [createLibrary, { isLoading, isSuccess }] = useCreateLibraryMutation();@@ -39,73 +29,43 @@ export function LibraryEmptyState() {}return (- <Card bg="background_page-primary" p={48} maw={640} mx="auto" withBorder>- <Stack gap="3rem">- <Stack gap="lg">- <Stack gap="sm">- <Title order={3}>{t`A source of truth for analytics`}</Title>- <Text c="text-secondary" lh="1.25rem">- {t`The semantic layer helps you create a source of truth for analytics by providing a centrally managed set of curated content. It separates authoritative, reusable components from ad-hoc analyses.`}- </Text>- </Stack>- <Stack gap="sm">- <Group gap="sm">- <Button- variant="filled"- onClick={handleSubmit}- loading={isLoading}- >{t`Create my semantic layer`}</Button>- </Group>- {error && <Text c="feedback-negative">{error}</Text>}- </Stack>+ <FeatureEmptyState+ title={t`A source of truth for analytics`}+ description={t`The semantic layer helps you create a source of truth for analytics by providing a centrally managed set of curated content. It separates authoritative, reusable components from ad-hoc analyses.`}+ actions={+ <Stack gap="sm">+ <Group gap="sm">+ <Button+ variant="filled"+ onClick={handleSubmit}+ loading={isLoading}+ >{t`Create my semantic layer`}</Button>+ </Group>+ {error && <Text c="feedback-negative">{error}</Text>}</Stack>- <SimpleGrid cols={2} spacing="sm">- <FeatureCard- icon="table"- title={t`Tables`}- description={t`Cleaned, pre-transformed data sources ready for exploring`}- />- <FeatureCard- icon="metric"- title={t`Metrics`}- description={t`Standardized calculations with known dimensions`}- />- <FeatureCard- icon="git_branch"- title={t`Version control`}- description={t`Sync your semantic layer to git`}- />- <FeatureCard- icon="verified_round"- title={t`High trust`}- description={t`Default to reliable sources your data team prescribes`}- />- </SimpleGrid>- </Stack>- </Card>- );-}--type FeatureCardProps = {- icon: IconName;- title: string;- description: string;-};--function FeatureCard({ icon, title, description }: FeatureCardProps) {- return (- <Paper bg="background_page-secondary" p="lg" radius="8px" shadow="none">- <Group gap="sm" align="flex-start" wrap="nowrap">- <Icon name={icon} size={16} c="core-brand" style={{ flexShrink: 0 }} />- <Stack gap="xxs">- <Text fw="bold" lh="1rem">- {title}- </Text>- <Text c="text-secondary" lh="1rem">- {description}- </Text>- </Stack>- </Group>- </Paper>+ }+ features={[+ {+ icon: "table",+ title: t`Tables`,+ description: t`Cleaned, pre-transformed data sources ready for exploring`,+ },+ {+ icon: "metric",+ title: t`Metrics`,+ description: t`Standardized calculations with known dimensions`,+ },+ {+ icon: "git_branch",+ title: t`Version control`,+ description: t`Sync your semantic layer to git`,+ },+ {+ icon: "verified_round",+ title: t`High trust`,+ description: t`Default to reliable sources your data team prescribes`,+ },+ ]}+ />);}diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/ManageDataAppGroupsPage-warnings.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/ManageDataAppGroupsPage-warnings.unit.spec.tsxdeleted file mode 100644index 9dd95759169..00000000000--- a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/ManageDataAppGroupsPage-warnings.unit.spec.tsx+++ /dev/null@@ -1,199 +0,0 @@-import userEvent from "@testing-library/user-event";-import fetchMock from "fetch-mock";--import { screen, waitFor, within } from "__support__/ui";-import { defer } from "metabase/utils/promise";-import type { DataAppGroupPermissionWarning } from "metabase-types/api";--import {- FINCHES_GROUP_ID,- OWLS_GROUP_ID,- openGroupAssignmentPicker,- setup,-} from "./tests/ManageDataAppGroupsPage.setup";--const FINCHES_WARNING = {- group_id: FINCHES_GROUP_ID,- missing_tables: [- {- id: 10,- name: "Orders",- schema: "public",- database_id: 1,- database_name: "Birds",- },- ],-};--describe("ManageDataAppGroupsPage warnings", () => {- it("shows missing tables for assigned groups on hover", async () => {- setup({- groups: [{ id: FINCHES_GROUP_ID, name: "Finches", member_count: 0 }],- warnings: [FINCHES_WARNING],- });-- await userEvent.hover(- await screen.findByRole("button", { name: "Missing data access" }),- );-- expect(- screen.getByRole("columnheader", { name: "Data access" }),- ).toBeInTheDocument();-- expect(- await screen.findByText(- "Finches doesn’t have permission to view these tables used in this app:",- ),- ).toBeInTheDocument();-- await userEvent.hover(screen.getByRole("link", { name: "Orders" }));-- const ordersLink = screen.getByRole("link", { name: "Orders" });- expect(ordersLink).toBeVisible();-- expect(ordersLink).toHaveAttribute(- "href",- expect.stringContaining("/admin/permissions/data"),- );-- // should not open in new tab- expect(ordersLink).not.toHaveAttribute("target");- });-- it("clears a removed group's warning", async () => {- setup({- groups: [- { id: FINCHES_GROUP_ID, name: "Finches", member_count: 0 },- { id: OWLS_GROUP_ID, name: "Owls", member_count: 2 },- ],- warnings: [FINCHES_WARNING],- });-- expect(- await within(- await screen.findByRole("row", { name: /Finches/ }),- ).findByRole("button", { name: "Missing data access" }),- ).toBeInTheDocument();-- await userEvent.click(- screen.getByRole("button", { name: "Remove Finches" }),- );-- // after group is removed, there should be no warning- await waitFor(() =>- expect(- screen.queryByRole("button", { name: "Missing data access" }),- ).not.toBeInTheDocument(),- );- });-- it("updates assignments while warning check is still pending", async () => {- const warningsResponse = defer<DataAppGroupPermissionWarning[]>();-- setup({- groups: [{ id: OWLS_GROUP_ID, name: "Owls", member_count: 2 }],- warningsResponse: warningsResponse.promise,- });-- try {- await openGroupAssignmentPicker();-- await userEvent.click(screen.getByRole("option", { name: "Finches" }));- await userEvent.click(screen.getByRole("button", { name: "Add" }));-- // without updating the cache, finches group never shows because- // RTK Query delays cache invalidation until the "group warning" request is done;- // see `onQueryStarted` in `api/data-app.ts`- expect(- await screen.findByRole("button", { name: "Remove Finches" }),- ).toBeInTheDocument();-- await userEvent.click(- screen.getByRole("button", { name: "Remove Owls" }),- );-- // owls group should be removed- await waitFor(() =>- expect(- screen.queryByRole("button", { name: "Remove Owls" }),- ).not.toBeInTheDocument(),- );-- expect(- screen.getByRole("button", { name: "Remove Finches" }),- ).toBeInTheDocument();-- await userEvent.click(- screen.getByRole("button", { name: "Remove Finches" }),- );-- // finches group should be removed- expect(- await screen.findByText("No groups have access yet"),- ).toBeInTheDocument();- } finally {- warningsResponse.resolve([]);- }- });-- it("shows a loading indicator until the warning check finishes", async () => {- const warningsResponse = defer<DataAppGroupPermissionWarning[]>();-- setup({- groups: [{ id: FINCHES_GROUP_ID, name: "Finches", member_count: 0 }],- warningsResponse: warningsResponse.promise,- });-- try {- expect(- await screen.findByLabelText("Checking data access"),- ).toBeInTheDocument();-- expect(- screen.getByRole("button", { name: "Remove Finches" }),- ).toBeEnabled();-- warningsResponse.resolve([FINCHES_WARNING]);-- expect(- await screen.findByRole("button", { name: "Missing data access" }),- ).toBeInTheDocument();-- // loading indicator should disappear after the warning check finishes- expect(- screen.queryByLabelText("Checking data access"),- ).not.toBeInTheDocument();- } finally {- warningsResponse.resolve([]);- }- });-- it("shows an error banner and retries the warning check", async () => {- setup({- groups: [{ id: FINCHES_GROUP_ID, name: "Finches", member_count: 0 }],- warningsError: true,- });-- const banner = await screen.findByRole("alert");- expect(banner).toHaveTextContent("Could not check data access");-- expect(- screen.getByRole("button", { name: "Remove Finches" }),- ).toBeEnabled();-- fetchMock.modifyRoute("data-app-group-permission-warnings", {- response: [FINCHES_WARNING],- });-- await userEvent.click(- within(banner).getByRole("button", { name: "Retry" }),- );-- // show the warning after retry succeeds- expect(- await screen.findByRole("button", { name: "Missing data access" }),- ).toBeInTheDocument();-- expect(screen.queryByRole("alert")).not.toBeInTheDocument();- });-});diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/ManageDataAppGroupsPage.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/ManageDataAppGroupsPage.tsxdeleted file mode 100644index 8fec2c44aec..00000000000--- a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/ManageDataAppGroupsPage.tsx+++ /dev/null@@ -1,126 +0,0 @@-import { useState } from "react";-import { t } from "ttag";--import { AdminPaneLayout } from "metabase/admin/components/AdminPaneLayout";-import { Breadcrumbs } from "metabase/common/components/Breadcrumbs";-import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";-import { useToast } from "metabase/common/hooks";-import { useParams } from "metabase/router";-import { SettingsPageWrapper } from "metabase/settings-components";-import { Box, Button, Stack, Text } from "metabase/ui";-import {- useAddDataAppGroupsMutation,- useGetDataAppGroupsQuery,- useListDataAppsQuery,- useRemoveDataAppGroupMutation,-} from "metabase-enterprise/api";-import type { DataAppGroup } from "metabase-types/api";--import { DataAppGroupList } from "./components/DataAppGroupList/DataAppGroupList";--export const ManageDataAppGroupsPage = () => {- const { slug = "" } = useParams<{ slug: string }>();-- const listQuery = useListDataAppsQuery();- const listGroupsQuery = useGetDataAppGroupsQuery(slug);-- const app = listQuery.data?.find((app) => app.name === slug);- const isAppMissing = listQuery.isSuccess && !app;-- const error =- listQuery.error ??- listGroupsQuery.error ??- (isAppMissing ? t`Data app not found.` : undefined);-- const isLoading = listQuery.isLoading || listGroupsQuery.isLoading;-- return (- <SettingsPageWrapper>- <LoadingAndErrorWrapper error={error} loading={isLoading}>- {app && listGroupsQuery.data && (- <DataAppGroups- appName={slug}- appTitle={app.display_name}- groups={listGroupsQuery.data}- />- )}- </LoadingAndErrorWrapper>- </SettingsPageWrapper>- );-};--const DataAppGroups = ({- appName,- appTitle,- groups,-}: {- appName: string;- appTitle: string;- groups: DataAppGroup[];-}) => {- const [sendToast] = useToast();- const [isAdding, setIsAdding] = useState(false);-- const [addGroups] = useAddDataAppGroupsMutation();- const [removeGroup] = useRemoveDataAppGroupMutation();-- const handleAddGroups = async (groupIds: number[]) => {- const { error } = await addGroups({ name: appName, group_ids: groupIds });-- if (error) {- sendToast({ message: t`Failed to add groups`, variant: "negative" });- return false;- }-- setIsAdding(false);-- return true;- };-- const handleRemoveGroup = async (group: DataAppGroup) => {- const { error } = await removeGroup({ name: appName, group_id: group.id });-- if (error) {- sendToast({ message: t`Failed to remove group`, variant: "negative" });- }-- return !error;- };-- return (- <Stack gap="xl">- <Box px="md">- <Breadcrumbs- crumbs={[[t`Data apps`, "/admin/settings/apps"], [appTitle]]}- size="large"- />- </Box>-- <AdminPaneLayout- title={- <Text component="span" fz="2rem" lh="2rem">- {t`Manage access to ${appTitle}`}- </Text>- }- titleActions={- <Button- variant="filled"- onClick={() => setIsAdding(true)}- disabled={isAdding}- >- {t`Add groups`}- </Button>- }- >- <DataAppGroupList- appName={appName}- isAdding={isAdding}- groups={groups}- onAddGroups={handleAddGroups}- onCancelAdd={() => setIsAdding(false)}- onRemoveGroup={handleRemoveGroup}- />- </AdminPaneLayout>- </Stack>- );-};diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/ManageDataAppGroupsPage.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/ManageDataAppGroupsPage.unit.spec.tsxdeleted file mode 100644index bd660eb2c8f..00000000000--- a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/ManageDataAppGroupsPage.unit.spec.tsx+++ /dev/null@@ -1,157 +0,0 @@-import userEvent from "@testing-library/user-event";-import fetchMock from "fetch-mock";--import { screen, waitFor, within } from "__support__/ui";-import { createMockDataApp } from "metabase-types/api/mocks";--import {- FINCHES_GROUP_ID,- OWLS_GROUP_ID,- openGroupAssignmentPicker,- setup,-} from "./tests/ManageDataAppGroupsPage.setup";--describe("ManageDataAppGroupsPage", () => {- it("manages assignments when the app is disabled", async () => {- setup({ app: createMockDataApp({ enabled: false }) });-- await openGroupAssignmentPicker();-- // can assign groups- await userEvent.click(screen.getByRole("option", { name: "Finches" }));- await userEvent.click(screen.getByRole("button", { name: "Add" }));-- expect(- await screen.findByRole("button", { name: "Remove Finches" }),- ).toBeInTheDocument();-- // can unassign groups- await userEvent.click(- screen.getByRole("button", { name: "Remove Finches" }),- );-- expect(- await screen.findByText("No groups have access yet"),- ).toBeInTheDocument();- });-- it("shows member counts and filters invalid and assigned groups", async () => {- setup({ groups: [{ id: OWLS_GROUP_ID, name: "Owls", member_count: 7 }] });-- expect(- await screen.findByText("Manage access to Sales"),- ).toBeInTheDocument();-- // member count should be visible- expect(screen.getByText("7")).toBeInTheDocument();-- await openGroupAssignmentPicker();-- expect(- screen.getByRole("option", { name: "All Users" }),- ).toBeInTheDocument();-- expect(screen.getByRole("option", { name: "Finches" })).toBeInTheDocument();-- // assigned groups, admins and tenant groups must not be selectable- for (const invalid of ["Owls", "Administrators", "Tenant"]) {- expect(- screen.queryByRole("option", { name: invalid }),- ).not.toBeInTheDocument();- }- });-- it("batch-assign selected groups", async () => {- setup();-- await openGroupAssignmentPicker();-- // assign these groups- await userEvent.click(screen.getByRole("option", { name: "Finches" }));- await userEvent.click(screen.getByRole("option", { name: "Owls" }));- await userEvent.click(screen.getByRole("button", { name: "Add" }));-- await waitFor(() => {- const requests = fetchMock.callHistory.calls(- "path:/api/ee/apps/sales/groups",- { method: "POST" },- );-- expect(- requests.map(({ options }) => JSON.parse(String(options.body))),- ).toEqual([{ group_ids: [FINCHES_GROUP_ID, OWLS_GROUP_ID] }]);- });-- expect(- await screen.findByRole("button", { name: "Remove Finches" }),- ).toBeInTheDocument();- });-- it("retries with the full selection if assigning group fails", async () => {- setup({ failFirstAdd: true });- await openGroupAssignmentPicker();-- await userEvent.click(screen.getByRole("option", { name: "Finches" }));- await userEvent.click(screen.getByRole("option", { name: "Owls" }));-- const addGroups = () =>- within(screen.getByTestId("data-app-groups-card")).getByRole("button", {- name: "Add",- });-- // first attempt should fail- await userEvent.click(addGroups());- expect(await screen.findByText("Failed to add groups")).toBeInTheDocument();-- expect(- screen.queryByRole("button", { name: "Remove Finches" }),- ).not.toBeInTheDocument();-- await userEvent.click(addGroups());-- // second retry attempt should pass- expect(- await screen.findByRole("button", { name: "Remove Finches" }),- ).toBeInTheDocument();-- const requests = fetchMock.callHistory.calls(- "path:/api/ee/apps/sales/groups",- { method: "POST" },- );-- expect(- requests.map(({ options }) => JSON.parse(String(options.body))),- ).toEqual([- { group_ids: [FINCHES_GROUP_ID, OWLS_GROUP_ID] },-- // second retry request should include the full selection- { group_ids: [FINCHES_GROUP_ID, OWLS_GROUP_ID] },- ]);- });-- it("returns to the previous page after removing the last group", async () => {- setup({- groups: Array.from({ length: 26 }, (_, index) => ({- id: index + 100,- name: `Group ${index + 1}`,- member_count: 0,- })),- });-- await userEvent.click(- await screen.findByRole("button", { name: "Next page" }),- );-- await userEvent.click(- screen.getByRole("button", { name: "Remove Group 26" }),- );-- expect(- await screen.findByRole("button", { name: "Remove Group 1" }),- ).toBeInTheDocument();-- expect(- screen.queryByRole("button", { name: "Remove Group 26" }),- ).not.toBeInTheDocument();- });-});diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/ManageDataAppsPage.module.css b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/ManageDataAppsPage.module.cssdeleted file mode 100644index f565ba6f50e..00000000000--- a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/ManageDataAppsPage.module.css+++ /dev/null@@ -1,3 +0,0 @@-.appList > *:not(:last-child) {- border-bottom: 1px solid var(--mb-color-border-neutral);-}diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/ManageDataAppsPage.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/ManageDataAppsPage.tsxdeleted file mode 100644index 35bd26eb818..00000000000--- a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/ManageDataAppsPage.tsx+++ /dev/null@@ -1,101 +0,0 @@-import { t } from "ttag";--import { DelayedLoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper/DelayedLoadingAndErrorWrapper";-import {- SettingsPageWrapper,- SettingsSection,-} from "metabase/settings-components";-import { Badge, Box, Group, Stack, Title } from "metabase/ui";-import {- useGetDataAppRepoStatusQuery,- useListDataAppsQuery,-} from "metabase-enterprise/api";--import S from "./ManageDataAppsPage.module.css";-import { DataAppListItem } from "./components/DataAppListItem/DataAppListItem";-import { DataAppRepoSection } from "./components/DataAppRepoSection/DataAppRepoSection";-import { DataAppSkillsSection } from "./components/DataAppSkillsSection/DataAppSkillsSection";-import { DataAppsEmptyState } from "./components/DataAppsEmptyState/DataAppsEmptyState";-import { DataAppsBanner } from "./components/DataAppsPromoBanner/DataAppsBanner";--const DATA_APP_REPO_QUERY_OPTS = {- // Keep the sync status fresh while the page is open: the backend polls the repo- // on its own schedule, so re-fetch the list periodically to reflect those syncs.- // Skipped automatically when the tab is unfocused.- pollingInterval: 10_000,- skipPollingIfUnfocused: true,- // Repo connection is managed on a different tab (Remote Sync) through another- // API slice, so it can't invalidate this cache. Refetch on mount so navigating- // (back) to the Data apps tab always reflects the current connection instead- // of a stale cached value.- refetchOnMountOrArgChange: true,-} as const;--export const ManageDataAppsPage = () => {- const {- data: status,- isLoading: isStatusLoading,- error: statusError,- } = useGetDataAppRepoStatusQuery(undefined, DATA_APP_REPO_QUERY_OPTS);- const {- data: apps = [],- isLoading: isAppsLoading,- error: appsError,- } = useListDataAppsQuery(undefined, DATA_APP_REPO_QUERY_OPTS);-- const isConfigured = status?.configured ?? false;- const isLoading = isStatusLoading || isAppsLoading;- const error = statusError ?? appsError;-- return (- <SettingsPageWrapper>- <Group gap="sm" align="center">- <Title order={1}>{t`Data apps`}</Title>-- <Badge>{t`Beta`}</Badge>- </Group>-- <DataAppsBanner />-- <Stack gap="lg">- <Title order={2}>{t`Setup`}</Title>-- <SettingsSection- stackProps={{- gap: "xl",- }}- >- <DataAppRepoSection isConfigured={isConfigured} url={status?.url} />-- <DataAppSkillsSection />- </SettingsSection>- </Stack>-- <Stack gap="lg">- <Title order={2}>{t`Apps`}</Title>-- <DelayedLoadingAndErrorWrapper loading={isLoading} error={error}>- {apps.length === 0 ? (- <DataAppsEmptyState />- ) : (- <Box- bd="1px solid var(--mb-color-border-neutral)"- bdrs="sm"- bg="background_page-primary"- className={S.appList}- style={{ overflow: "hidden" }}- >- {apps.map((app) => (- <DataAppListItem- key={app.id}- app={app}- canRemove={!isConfigured}- />- ))}- </Box>- )}- </DelayedLoadingAndErrorWrapper>- </Stack>- </SettingsPageWrapper>- );-};diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/ManageDataAppsPage.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/ManageDataAppsPage.unit.spec.tsxdeleted file mode 100644index 205e8de57cd..00000000000--- a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/ManageDataAppsPage.unit.spec.tsx+++ /dev/null@@ -1,286 +0,0 @@-import userEvent from "@testing-library/user-event";-import fetchMock from "fetch-mock";--import {- setupDataAppRepoStatusEndpoint,- setupDataAppRepoStatusEndpointWithError,- setupDeleteDataAppEndpoint,- setupListDataAppsEndpoint,- setupListDataAppsEndpointWithError,- setupUpdateDataAppEndpoint,- setupUserAcknowledgementEndpoints,-} from "__support__/server-mocks";-import { renderWithProviders, screen, within } from "__support__/ui";-import { UndoListing } from "metabase/common/components/UndoListing";-import { Route } from "metabase/router";-import type { DataApp } from "metabase-types/api";-import { createMockDataApp } from "metabase-types/api/mocks";--import { ManageDataAppsPage } from "./ManageDataAppsPage";--type SetupOpts = {- configured?: boolean;- url?: string | null;- apps?: DataApp[];- updatedApp?: DataApp;- appsError?: boolean;- statusError?: boolean;-};--const setup = ({- configured = true,- url = null,- apps = [],- updatedApp,- appsError = false,- statusError = false,-}: SetupOpts = {}) => {- apps.forEach((app) => setupDeleteDataAppEndpoint(app.name));-- if (updatedApp) {- setupUpdateDataAppEndpoint(updatedApp);- }-- if (statusError) {- setupDataAppRepoStatusEndpointWithError("Repo status failed to load");- } else {- setupDataAppRepoStatusEndpoint({ configured, url });- }-- if (appsError) {- setupListDataAppsEndpointWithError("Apps failed to load");- } else {- setupListDataAppsEndpoint(apps);- }-- setupUserAcknowledgementEndpoints({- key: "data-apps-admin-settings-banner",- value: true,- });-- const Page = () => (- <>- <ManageDataAppsPage />- <UndoListing />- </>- );-- renderWithProviders(<Route path="/" element={<Page />} />, {- withRouter: true,- });-};--const openActionsMenu = async (displayName: string) =>- userEvent.click(- await screen.findByRole("button", { name: `Actions for ${displayName}` }),- );--describe("ManageDataAppsPage", () => {- describe("empty states", () => {- it("shows the generic empty state, and no duplicate 'no repository' message, when no repo is connected", async () => {- setup({ configured: false });-- expect(- await screen.findByText("Your data apps will appear here"),- ).toBeInTheDocument();- expect(- screen.queryByText(/No repository is connected yet/),- ).not.toBeInTheDocument();- });-- it("shows the empty state when a connected repository has no apps", async () => {- const url = "https://github.com/metabase/stats-remote-sync";- setup({ configured: true, url });-- expect(await screen.findByText(url)).toBeInTheDocument();- expect(- await screen.findByText("Your data apps will appear here"),- ).toBeInTheDocument();- });-- it("shows the setup section: repo status, the Git sync link, and the install command", async () => {- setup({ configured: false });-- expect(- await screen.findByText("No repository connected"),- ).toBeInTheDocument();- expect(- screen.getByRole("link", { name: "Go to Git sync settings" }),- ).toHaveAttribute("href", "/admin/settings/remote-sync");- expect(- screen.getByText(- /npx skills add metabase\/agent-skills\/skills\/metabase-data-apps\/v1/,- ),- ).toBeInTheDocument();- });- });-- describe("the app list", () => {- it("shows an error instead of the list when the apps request fails", async () => {- setup({ appsError: true });-- expect(- await screen.findByText("Apps failed to load"),- ).toBeInTheDocument();- expect(- screen.queryByText("Your data apps will appear here"),- ).not.toBeInTheDocument();- });-- it("shows an error instead of the list when the repo status request fails", async () => {- setup({ statusError: true });-- expect(- await screen.findByText("Repo status failed to load"),- ).toBeInTheDocument();- expect(- screen.queryByText("Your data apps will appear here"),- ).not.toBeInTheDocument();- });-- it("links an enabled app to its route and shows its path", async () => {- setup({ apps: [createMockDataApp({ name: "sales" })] });-- expect(- await screen.findByRole("link", { name: "Sales" }),- ).toHaveAttribute("href", "/apps/sales");- expect(screen.getByText("/apps/sales")).toBeInTheDocument();- });-- it("shows a disabled app as plain text with a Disabled badge", async () => {- setup({ apps: [createMockDataApp({ name: "sales", enabled: false })] });-- expect(await screen.findByText("Sales")).toBeInTheDocument();- // A disabled app isn't reachable, so its name isn't a link.- expect(- screen.queryByRole("link", { name: "Sales" }),- ).not.toBeInTheDocument();- expect(screen.getByText("Disabled")).toBeInTheDocument();- });-- it("shows an outdated app as plain text with an Outdated badge", async () => {- setup({- apps: [- createMockDataApp({ name: "sales", version: 1, outdated: true }),- ],- });-- expect(await screen.findByText("Sales")).toBeInTheDocument();- expect(- screen.queryByRole("link", { name: "Sales" }),- ).not.toBeInTheDocument();- expect(screen.getByText("Outdated")).toBeInTheDocument();- expect(screen.queryByText("Disabled")).not.toBeInTheDocument();- });-- it("gives every app its own actions menu", async () => {- setup({- apps: [- createMockDataApp({- id: 1,- name: "alpha",- display_name: "Alpha App",- }),- createMockDataApp({ id: 2, name: "beta", display_name: "Beta App" }),- ],- });-- expect(- await screen.findByRole("link", { name: "Alpha App" }),- ).toBeInTheDocument();- expect(- screen.getByRole("link", { name: "Beta App" }),- ).toBeInTheDocument();- expect(- screen.getByRole("button", { name: "Actions for Alpha App" }),- ).toBeInTheDocument();- expect(- screen.getByRole("button", { name: "Actions for Beta App" }),- ).toBeInTheDocument();- });-- it("shows how many hosts an app is allowed to reach", async () => {- setup({- apps: [- createMockDataApp({- allowed_hosts: ["https://api.example.com", "https://*.acme.com"],- }),- ],- });-- expect(await screen.findByText("2 allowed hosts")).toBeInTheDocument();- });- });-- describe("actions", () => {- it("disables an app", async () => {- setup({- apps: [createMockDataApp({ name: "sales" })],- updatedApp: createMockDataApp({ name: "sales", enabled: false }),- });-- await openActionsMenu("Sales");- await userEvent.click(- await screen.findByRole("menuitem", { name: "Disable" }),- );-- const request = fetchMock.callHistory.lastCall("path:/api/ee/apps/sales");- expect(await request?.request?.json()).toEqual({ enabled: false });- });-- it("re-enables a disabled app", async () => {- setup({- apps: [createMockDataApp({ name: "sales", enabled: false })],- updatedApp: createMockDataApp({ name: "sales" }),- });-- await openActionsMenu("Sales");- await userEvent.click(- await screen.findByRole("menuitem", { name: "Re-enable" }),- );-- const request = fetchMock.callHistory.lastCall("path:/api/ee/apps/sales");- expect(await request?.request?.json()).toEqual({ enabled: true });- });-- it("offers no Remove while a repository is connected", async () => {- // A removed app would just come back on the next sync, so Remove is only- // offered once the repo is unlinked.- setup({ configured: true, apps: [createMockDataApp({ name: "sales" })] });-- await openActionsMenu("Sales");-- expect(- await screen.findByRole("menuitem", { name: "Disable" }),- ).toBeInTheDocument();- expect(- screen.queryByRole("menuitem", { name: "Remove" }),- ).not.toBeInTheDocument();- });-- it("removes an app once the repository is unlinked", async () => {- // Unlinked, there's no sync to prune it, so an app synced while a repo was- // connected stays listed — with a Remove action to clear it out.- setup({- configured: false,- apps: [createMockDataApp({ name: "sales" })],- });-- await openActionsMenu("Sales");- await userEvent.click(- await screen.findByRole("menuitem", { name: "Remove" }),- );- await userEvent.click(- within(await screen.findByRole("dialog")).getByRole("button", {- name: "Remove",- }),- );-- expect(- fetchMock.callHistory.called("path:/api/ee/apps/sales", {- method: "DELETE",- }),- ).toBe(true);- });- });-});diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/AddDataAppGroups/AddDataAppGroups.module.css b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/AddDataAppGroups/AddDataAppGroups.module.cssdeleted file mode 100644index 089b36c0fc2..00000000000--- a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/AddDataAppGroups/AddDataAppGroups.module.css+++ /dev/null@@ -1,29 +0,0 @@-.row {- border: 1px solid var(--mb-color-border-neutral);- border-radius: 0.5rem;-}--.row .pill {- padding: 0.375rem 0.75rem;- gap: 0.375rem;- font-size: var(--mantine-font-size-md);-}--.row .pill[data-with-remove] {- padding-inline-end: var(--mantine-spacing-sm);-}--.row[data-has-current-groups="true"] {- border-radius: 0.5rem 0.5rem 0 0;-}--.row:focus-within {- border-color: var(--mb-color-core-brand);-}--.row[data-has-current-groups="true"]:focus-within {- box-shadow:- inset 1px 0 0 var(--mb-color-core-brand),- inset -1px 0 0 var(--mb-color-core-brand),- inset 0 1px 0 var(--mb-color-core-brand);-}diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/AddDataAppGroups/AddDataAppGroups.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/AddDataAppGroups/AddDataAppGroups.tsxdeleted file mode 100644index 708c23a3f5f..00000000000--- a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/AddDataAppGroups/AddDataAppGroups.tsx+++ /dev/null@@ -1,119 +0,0 @@-import { useMemo, useState } from "react";-import { t } from "ttag";--import { useListPermissionsGroupsQuery } from "metabase/api";-import {- getGroupNameLocalized,- isAdminGroup,-} from "metabase/common/utils/groups";-import { Alert, Button, Group, MultiSelect, Stack } from "metabase/ui";-import type { DataAppGroup } from "metabase-types/api";--import S from "./AddDataAppGroups.module.css";--type Props = {- groups: DataAppGroup[];-- onCancel: () => void;- onAddGroups: (groupIds: number[]) => Promise<boolean>;-};--export const AddDataAppGroups = ({ groups, onAddGroups, onCancel }: Props) => {- const [selectedIds, setSelectedIds] = useState<string[]>([]);- const [isSubmitting, setIsSubmitting] = useState(false);-- const groupsQuery = useListPermissionsGroupsQuery({ tenancy: "internal" });-- const selectableGroupOptions = useMemo(- () =>- groupsQuery.data- ?.filter(- (group) =>- !group.is_tenant_group &&- !isAdminGroup(group) &&- !groups.some((assigned) => assigned.id === group.id),- )- .map((group) => ({- value: String(group.id),- label: getGroupNameLocalized(group),- })),- [groupsQuery.data, groups],- );-- const handleSubmit = async () => {- setIsSubmitting(true);-- try {- const success = await onAddGroups(selectedIds.map(Number));-- if (success) {- setSelectedIds([]);- }- } finally {- setIsSubmitting(false);- }- };-- return (- <Stack gap="md">- <Group- className={S.row}- data-has-current-groups={groups.length > 0}- mx={groups.length > 0 ? "-1px" : 0}- mt={groups.length > 0 ? "-1px" : 0}- p="0.5rem"- pr="md"- gap={0}- align="center"- wrap="nowrap"- >- <MultiSelect- flex={1}- miw={0}- variant="unstyled"- rightSection={null}- classNames={{ pill: S.pill }}- comboboxProps={{- withinPortal: true,- keepMounted: false,-- // Leave a gap beyond the surrounding row's padding and border.- offset: 18,- }}- styles={MULTI_SELECT_STYLES}- aria-label={t`Search for groups to add`}- placeholder={t`Search for groups to add`}- searchable- maxValues={100}- data={selectableGroupOptions}- value={selectedIds}- onChange={setSelectedIds}- disabled={isSubmitting || groupsQuery.isLoading}- />-- <Button- variant="subtle"- color="neutral"- mr="sm"- onClick={onCancel}- disabled={isSubmitting}- >{t`Cancel`}</Button>-- <Button- variant={selectedIds.length > 0 ? "filled" : "default"}- onClick={handleSubmit}- loading={isSubmitting}- disabled={!selectedIds.length}- >{t`Add`}</Button>- </Group>-- {groupsQuery.isError && (- <Alert color="error">{t`Could not load groups`}</Alert>- )}- </Stack>- );-};--const MULTI_SELECT_STYLES = {- input: { background: "transparent", fontSize: "var(--mantine-font-size-lg)" },-};diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppActionsMenu/DataAppActionsMenu.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppActionsMenu/DataAppActionsMenu.tsxdeleted file mode 100644index 8cb80cfe746..00000000000--- a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppActionsMenu/DataAppActionsMenu.tsx+++ /dev/null@@ -1,93 +0,0 @@-import { useCallback } from "react";-import { t } from "ttag";--import { useConfirmation, useToast } from "metabase/common/hooks";-import { Link } from "metabase/router";-import { ActionIcon, Icon, Menu } from "metabase/ui";-import {- useDeleteDataAppMutation,- useSetDataAppEnabledMutation,-} from "metabase-enterprise/api";-import type { DataApp } from "metabase-types/api";--type Props = {- app: DataApp;- canRemove?: boolean;-};--export const DataAppActionsMenu = ({ app, canRemove = false }: Props) => {- const [setEnabled] = useSetDataAppEnabledMutation();- const [deleteDataApp, { isLoading: isDeleting }] = useDeleteDataAppMutation();- const [sendToast] = useToast();- const { show: showConfirmation, modalContent: confirmationModal } =- useConfirmation();-- const handleToggleEnabled = useCallback(async () => {- try {- await setEnabled({ name: app.name, enabled: !app.enabled }).unwrap();- } catch {- sendToast({ message: t`Failed to update this app`, variant: "negative" });- }- }, [app.name, app.enabled, setEnabled, sendToast]);-- const handleRemove = useCallback(() => {- showConfirmation({- title: t`Remove ${app.display_name} app?`,- message: t`This removes the data app, which won't be reachable until it's synced again from a connected repository.`,- confirmButtonText: t`Remove`,- onConfirm: async () => {- try {- await deleteDataApp(app.name).unwrap();- } catch {- sendToast({- message: t`Failed to remove this data app`,- variant: "negative",- });- }- },- });- }, [app.display_name, app.name, deleteDataApp, sendToast, showConfirmation]);-- return (- <>- <Menu position="bottom-end">- <Menu.Target>- <ActionIcon- aria-label={t`Actions for ${app.display_name}`}- variant="subtle"- c="text-secondary"- loading={isDeleting}- >- <Icon name="ellipsis" />- </ActionIcon>- </Menu.Target>-- <Menu.Dropdown>- <Menu.Item- component={Link}- to={`/collection/${app.resource_collection_id}`}- >- {t`View resources`}- </Menu.Item>-- <Menu.Item- component={Link}- to={`/admin/settings/apps/${encodeURIComponent(app.name)}/groups`}- >- {t`Manage group access`}- </Menu.Item>-- <Menu.Item onClick={handleToggleEnabled}>- {app.enabled ? t`Disable` : t`Re-enable`}- </Menu.Item>-- {canRemove && (- <Menu.Item onClick={handleRemove}>{t`Remove`}</Menu.Item>- )}- </Menu.Dropdown>- </Menu>-- {confirmationModal}- </>- );-};diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppActionsMenu/DataAppActionsMenu.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppActionsMenu/DataAppActionsMenu.unit.spec.tsxdeleted file mode 100644index 9bb1b2cbc5e..00000000000--- a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppActionsMenu/DataAppActionsMenu.unit.spec.tsx+++ /dev/null@@ -1,127 +0,0 @@-import userEvent from "@testing-library/user-event";-import fetchMock from "fetch-mock";--import { renderWithProviders, screen, waitFor, within } from "__support__/ui";-import { UndoListing } from "metabase/common/components/UndoListing";-import { createMockDataApp } from "metabase-types/api/mocks";--import { DataAppActionsMenu } from "./DataAppActionsMenu";--const setup = ({- enabled = true,- canRemove = false,- resourceCollectionId = 9,-}: {- enabled?: boolean;- canRemove?: boolean;- resourceCollectionId?: number;-} = {}) => {- const app = createMockDataApp({- name: "sales",- display_name: "Sales",- enabled,- resource_collection_id: resourceCollectionId,- });- renderWithProviders(- <>- <DataAppActionsMenu app={app} canRemove={canRemove} />- {/* Mounts the toaster so failure toasts are assertable in the DOM. */}- <UndoListing />- </>,- { withRouter: true },- );-};--const openMenu = () =>- userEvent.click(screen.getByRole("button", { name: "Actions for Sales" }));--const confirmRemove = async () =>- userEvent.click(- within(await screen.findByRole("dialog")).getByRole("button", {- name: "Remove",- }),- );--describe("DataAppActionsMenu", () => {- it("links to the app's resources and group above the enable action", async () => {- setup();-- await openMenu();-- const menuItems = await screen.findAllByRole("menuitem");- expect(menuItems).toHaveLength(3);-- const [viewResource, manageAccess, disable] = menuItems;-- expect(viewResource).toHaveTextContent("View resources");- expect(viewResource).toHaveAttribute("href", "/collection/9");-- expect(manageAccess).toHaveTextContent("Manage group access");- expect(manageAccess).toHaveAttribute(- "href",- "/admin/settings/apps/sales/groups",- );-- expect(disable).toHaveTextContent("Disable");- });-- it("should show a toast when toggling enabled fails", async () => {- fetchMock.put("path:/api/ee/apps/sales", 500);- setup({ enabled: true });-- await openMenu();- await userEvent.click(- await screen.findByRole("menuitem", { name: "Disable" }),- );-- expect(- await screen.findByText("Failed to update this app"),- ).toBeInTheDocument();- });-- it("should show a toast when removal fails", async () => {- fetchMock.delete("path:/api/ee/apps/sales", 500);- setup({ canRemove: true });-- await openMenu();- await userEvent.click(- await screen.findByRole("menuitem", { name: "Remove" }),- );- await confirmRemove();-- expect(- await screen.findByText("Failed to remove this data app"),- ).toBeInTheDocument();- });-- it("should show a loading state on the trigger while a delete is in flight", async () => {- let finishDelete = () => {};- fetchMock.delete(- "path:/api/ee/apps/sales",- () =>- new Promise(- (resolve) => (finishDelete = () => resolve({ status: 204 })),- ),- );- setup({ canRemove: true });-- await openMenu();- await userEvent.click(- await screen.findByRole("menuitem", { name: "Remove" }),- );- await confirmRemove();-- const trigger = () =>- screen.getByRole("button", { name: "Actions for Sales" });-- // Mantine marks a loading ActionIcon with `data-loading`.- await waitFor(() =>- expect(trigger()).toHaveAttribute("data-loading", "true"),- );-- finishDelete();- await waitFor(() =>- expect(trigger()).not.toHaveAttribute("data-loading", "true"),- );- });-});diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppAllowedHosts/DataAppAllowedHosts.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppAllowedHosts/DataAppAllowedHosts.tsxdeleted file mode 100644index e1e0aeab435..00000000000--- a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppAllowedHosts/DataAppAllowedHosts.tsx+++ /dev/null@@ -1,49 +0,0 @@-import { msgid, ngettext } from "ttag";--import { HoverCard, Stack, Text } from "metabase/ui";--type Props = {- /** External origins the app may fetch/XHR (from `data_app.yaml`). */- hosts: string[];-};--/**- * The app's network allowlist, shown inline in the admin list as an underlined- * "N allowed hosts" that reveals the origins in a hover card. Renders nothing- * when the app declares no allowed hosts.- */-export function DataAppAllowedHosts({ hosts }: Props) {- if (hosts.length === 0) {- return null;- }-- const label = ngettext(- msgid`${hosts.length} allowed host`,- `${hosts.length} allowed hosts`,- hosts.length,- );-- return (- <HoverCard position="bottom-start">- <HoverCard.Target>- <Text- size="sm"- c="text-secondary"- lh="1.4"- style={{ textDecoration: "underline dotted", cursor: "help" }}- >- {label}- </Text>- </HoverCard.Target>- <HoverCard.Dropdown p="sm">- <Stack gap="xxs">- {hosts.map((host, index) => (- <Text key={`${index}-${host}`} ff="monospace" size="sm">- {host}- </Text>- ))}- </Stack>- </HoverCard.Dropdown>- </HoverCard>- );-}diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppAllowedHosts/DataAppAllowedHosts.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppAllowedHosts/DataAppAllowedHosts.unit.spec.tsxdeleted file mode 100644index 01348902746..00000000000--- a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppAllowedHosts/DataAppAllowedHosts.unit.spec.tsx+++ /dev/null@@ -1,40 +0,0 @@-import userEvent from "@testing-library/user-event";--import { renderWithProviders, screen } from "__support__/ui";--import { DataAppAllowedHosts } from "./DataAppAllowedHosts";--describe("DataAppAllowedHosts", () => {- it("renders nothing when there are no allowed hosts", () => {- renderWithProviders(<DataAppAllowedHosts hosts={[]} />);-- expect(screen.queryByText(/allowed host/)).not.toBeInTheDocument();- });-- it("shows a singular label for a single host", () => {- renderWithProviders(- <DataAppAllowedHosts hosts={["https://api.example.com"]} />,- );-- expect(screen.getByText("1 allowed host")).toBeInTheDocument();- });-- it("shows a pluralized count and reveals the hosts on hover", async () => {- renderWithProviders(- <DataAppAllowedHosts- hosts={["https://api.example.com", "https://*.acme.com"]}- />,- );-- const label = screen.getByText("2 allowed hosts");- expect(label).toBeInTheDocument();-- // The origins live in a hover card that opens on pointer hover.- await userEvent.hover(label);-- expect(- await screen.findByText("https://api.example.com"),- ).toBeInTheDocument();- expect(screen.getByText("https://*.acme.com")).toBeInTheDocument();- });-});diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppDataAccessWarning/DataAppDataAccessWarning.module.css b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppDataAccessWarning/DataAppDataAccessWarning.module.cssdeleted file mode 100644index e321b7543d0..00000000000--- a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppDataAccessWarning/DataAppDataAccessWarning.module.css+++ /dev/null@@ -1,13 +0,0 @@-.badge {- background-color: var(--mb-color-background_surface-warning-strong);- transition: background-color 150ms ease;-}--.button {- cursor: pointer;-}--.button:hover .badge,-.button:focus-visible .badge {- background-color: var(--mb-color-background_surface-warning);-}diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppDataAccessWarning/DataAppDataAccessWarning.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppDataAccessWarning/DataAppDataAccessWarning.tsxdeleted file mode 100644index a35008d2149..00000000000--- a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppDataAccessWarning/DataAppDataAccessWarning.tsx+++ /dev/null@@ -1,135 +0,0 @@-import { t } from "ttag";--import { getDatabaseFocusPermissionsUrl } from "metabase/admin/permissions/utils/urls";-import { Link } from "metabase/router";-import {- Anchor,- Badge,- Flex,- HoverCard,- Icon,- Stack,- Text,- UnstyledButton,-} from "metabase/ui";-import type {- DataAppGroupPermissionWarning,- DataAppMissingTable,-} from "metabase-types/api";--import S from "./DataAppDataAccessWarning.module.css";--interface Props {- warning: DataAppGroupPermissionWarning;- groupName: string;-}--export const DataAppDataAccessWarning = ({ warning, groupName }: Props) => {- const label = t`Missing data access`;-- return (- <HoverCard position="bottom-end" shadow="md">- <HoverCard.Target>- <UnstyledButton- className={S.button}- aria-label={label}- style={{ flexShrink: 0 }}- >- <Badge- className={S.badge}- size="sm"- c="text-primary"- bdrs="sm"- tt="none"- >- {label}- </Badge>- </UnstyledButton>- </HoverCard.Target>-- <HoverCard.Dropdown- p="lg"- w="30rem"- data-testid="data-access-warning-popover"- >- <Stack gap="lg">- <Text size="sm">- {t`${groupName} doesn’t have permission to view these tables used in this app:`}- </Text>-- <Stack- component="ul"- data-testid="missing-tables-list"- gap="sm"- m={0}- pl={0}- style={{ listStyle: "none" }}- >- {warning.missing_tables.map((table) => {- const parts = getMissingTableSegments(table);-- return (- <Flex- component="li"- key={table.id}- align="center"- gap={4}- wrap="wrap"- >- {parts.map((part, index) => (- <Flex key={part.url} align="center" gap={4}>- <Anchor component={Link} to={part.url} size="sm" fw={700}>- {part.label}- </Anchor>-- {index < parts.length - 1 && (- <Icon- name="chevronright"- size={12}- c="text-secondary"- aria-hidden- />- )}- </Flex>- ))}- </Flex>- );- })}- </Stack>- </Stack>- </HoverCard.Dropdown>- </HoverCard>- );-};--const getMissingTableSegments = (table: DataAppMissingTable) => {- const databaseSection = {- label: table.database_name,- url: getDatabaseFocusPermissionsUrl({- databaseId: table.database_id,- }),- };-- const schemaSection = table.schema- ? [- {- label: table.schema,- url: getDatabaseFocusPermissionsUrl({- databaseId: table.database_id,- schemaName: table.schema,- }),- },- ]- : [];-- const tableSection = {- label: table.name,- url: getDatabaseFocusPermissionsUrl({- databaseId: table.database_id,- schemaName: table.schema ?? undefined,- tableId: table.id,- }),- };-- return [databaseSection, ...schemaSection, tableSection];-};diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppGroupList/DataAppGroupList.module.css b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppGroupList/DataAppGroupList.module.cssdeleted file mode 100644index abb99e40944..00000000000--- a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppGroupList/DataAppGroupList.module.css+++ /dev/null@@ -1,28 +0,0 @@-.groupListContent {- display: flex;- flex-direction: column;- gap: var(--mantine-spacing-lg);-}--.groupListContent.overlappingGroupListContent {- display: grid;-}--/**- Overlap the group card and empty state, so the- collapsing empty state does not add a second row- when transitioning from and to empty states- */-.overlappingGroupListContent > * {- grid-area: 1 / 1;-}--.groupTable tbody tr:not(:last-child) {- border-bottom: 1px solid var(--mb-color-border-neutral);-}--.removeGroupButton {- display: flex;- align-items: center;- justify-content: center;-}diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppGroupList/DataAppGroupList.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppGroupList/DataAppGroupList.tsxdeleted file mode 100644index ef5ad67f1ae..00000000000--- a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppGroupList/DataAppGroupList.tsx+++ /dev/null@@ -1,254 +0,0 @@-import { skipToken } from "@reduxjs/toolkit/query";-import cx from "classnames";-import { useEffect, useMemo } from "react";-import { t } from "ttag";--import NoResults from "assets/img/no_results.svg";-import { AdminContentTable } from "metabase/admin/components/AdminContentTable";-import { EmptyState } from "metabase/common/components/EmptyState";-import { PaginationControls } from "metabase/common/components/PaginationControls";-import { usePagination } from "metabase/common/hooks/use-pagination";-import { getGroupNameLocalized } from "metabase/common/utils/groups";-import Animation from "metabase/css/core/animation.module.css";-import {- Alert,- Anchor,- Box,- Collapse,- Flex,- Icon,- Loader,- Stack,- Text,- UnstyledButton,-} from "metabase/ui";-import { useGetDataAppGroupPermissionWarningsQuery } from "metabase-enterprise/api";-import type {- DataAppGroup,- DataAppGroupPermissionWarning,-} from "metabase-types/api";--import { AddDataAppGroups } from "../AddDataAppGroups/AddDataAppGroups";-import { DataAppDataAccessWarning } from "../DataAppDataAccessWarning/DataAppDataAccessWarning";--import S from "./DataAppGroupList.module.css";--const PAGE_SIZE = 25;--type Props = {- appName: string;- isAdding: boolean;- groups: DataAppGroup[];-- onCancelAdd: () => void;- onAddGroups: (groupIds: number[]) => Promise<boolean>;- onRemoveGroup: (group: DataAppGroup) => Promise<boolean>;-};--export const DataAppGroupList = ({- appName,- isAdding,- groups,- onAddGroups,- onCancelAdd,- onRemoveGroup,-}: Props) => {- const { handleNextPage, handlePreviousPage, page, setPage } = usePagination();-- const lastPage = Math.max(0, Math.ceil(groups.length / PAGE_SIZE) - 1);-- // make sure user does not stay in an empty page if the- // removed group is the last one in the page- useEffect(() => {- setPage((page) => Math.min(page, lastPage));- }, [lastPage, setPage]);-- const visibleGroups = useMemo(- () => groups.slice(page * PAGE_SIZE, (page + 1) * PAGE_SIZE),- [groups, page],- );-- const warningsQuery = useGetDataAppGroupPermissionWarningsQuery(- groups.length > 0 ? appName : skipToken,- { refetchOnMountOrArgChange: true },- );-- const warningsByGroupId = useMemo(- () =>- new Map(- warningsQuery.currentData?.map((warning) => [- warning.group_id,- warning,- ]),- ),- [warningsQuery.currentData],- );-- return (- <Stack data-testid="group-management-sections" gap="lg">- {groups.length > 0 && warningsQuery.isError && (- <Alert- color="error"- icon={<Icon name="warning" />}- size="compact"- styles={{ wrapper: { alignItems: "center" } }}- >- {t`Could not check data access`}-- <Anchor- component="button"- inherit- ml="0.5rem"- c="core-brand"- fw={700}- disabled={warningsQuery.isFetching}- onClick={() => warningsQuery.refetch()}- >{t`Retry`}</Anchor>- </Alert>- )}-- {groups.length > 0 && warningsQuery.isLoading && (- <Flex align="center" gap="sm">- <Loader size="xs" aria-label={t`Checking data access`} />- <Text c="text-secondary">{t`Checking data access…`}</Text>- </Flex>- )}-- <Box- className={cx(- S.groupListContent,-- // transitions between empty state and group list content- !isAdding && S.overlappingGroupListContent,- )}- >- {(isAdding || groups.length > 0) && (- <Box- data-testid="data-app-groups-card"- bd={- groups.length > 0 ? "1px solid var(--mb-color-border-neutral)" : 0- }- bdrs="sm"- bg="background_page-primary"- style={{ overflow: "hidden" }}- >- {isAdding && (- <AddDataAppGroups- groups={groups}- onAddGroups={onAddGroups}- onCancel={onCancelAdd}- />- )}-- {groups.length > 0 && (- <AdminContentTable- className={cx(S.groupTable, Animation.fadeIn)}- columnTitles={[t`Group name`, t`Members`, t`Data access`, null]}- >- {visibleGroups.map((group) => (- <GroupRow- key={group.id}- group={group}- warning={warningsByGroupId.get(group.id)}- onRemove={onRemoveGroup}- />- ))}- </AdminContentTable>- )}-- {groups.length > PAGE_SIZE && (- <Flex align="center" justify="flex-end" p="md">- <PaginationControls- page={page}- pageSize={PAGE_SIZE}- itemsLength={visibleGroups.length}- total={groups.length}- onNextPage={handleNextPage}- onPreviousPage={handlePreviousPage}- />- </Flex>- )}- </Box>- )}-- <Collapse- in={groups.length === 0}- transitionDuration={150}- transitionTimingFunction="ease-out"- >- <DataAppGroupsEmptyState />- </Collapse>- </Box>- </Stack>- );-};--const DataAppGroupsEmptyState = () => (- <Box- data-testid="data-app-groups-empty-state"- bg="background_page-secondary"- bdrs="md"- py="5rem"- >- <EmptyState- title={t`No groups have access yet`}- spacing="sm"- illustrationElement={- <img- src={NoResults}- alt={t`No results`}- width={120}- height={120}- data-testid="data-app-groups-empty-state-icon"- />- }- />- </Box>-);--const GroupRow = ({- group,- warning,- onRemove,-}: {- group: DataAppGroup;- warning?: DataAppGroupPermissionWarning;- onRemove: (group: DataAppGroup) => void;-}) => {- const name = getGroupNameLocalized(group);-- return (- <tr>- <td>- <Text fw={700}>{name}</Text>- </td>-- <td>{group.member_count}</td>-- <td>- {warning && (- <DataAppDataAccessWarning warning={warning} groupName={name} />- )}- </td>-- <Box component="td" w="1%" style={{ whiteSpace: "nowrap" }}>- <Flex- data-testid="data-app-group-actions"- align="center"- justify="flex-end"- gap="lg"- wrap="nowrap"- style={{ minWidth: "max-content" }}- >- <UnstyledButton- className={S.removeGroupButton}- aria-label={t`Remove ${name}`}- onClick={() => onRemove(group)}- >- <Icon name="close" c="text-disabled" size={16} />- </UnstyledButton>- </Flex>- </Box>- </tr>- );-};diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppIcon/DataAppIcon.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppIcon/DataAppIcon.tsxdeleted file mode 100644index ad26fe61cef..00000000000--- a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppIcon/DataAppIcon.tsx+++ /dev/null@@ -1,20 +0,0 @@-import { Flex, Icon } from "metabase/ui";--const ICON_SIZE = 20;--export function DataAppIcon() {- return (- <Flex- align="center"- justify="center"- w="2.75rem"- h="2.75rem"- bd="1px solid var(--mb-color-border-neutral)"- bg="background_page-secondary"- visibleFrom="sm"- style={{ borderRadius: "50%", flexShrink: 0 }}- >- <Icon name="app" size={ICON_SIZE} c="text-secondary" />- </Flex>- );-}diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppListItem/DataAppListItem.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppListItem/DataAppListItem.tsxdeleted file mode 100644index d5b9b5bd4ac..00000000000--- a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppListItem/DataAppListItem.tsx+++ /dev/null@@ -1,29 +0,0 @@-import { Flex, Group } from "metabase/ui";-import type { DataApp } from "metabase-types/api";--import { DataAppActionsMenu } from "../DataAppActionsMenu/DataAppActionsMenu";-import { DataAppStatusBadge } from "../DataAppStatusBadge/DataAppStatusBadge";-import { DataAppSummary } from "../DataAppSummary/DataAppSummary";--type Props = {- app: DataApp;- canRemove?: boolean;-};--export const DataAppListItem = ({ app, canRemove = false }: Props) => (- <Flex- data-testid={`data-app-list-item-${app.name}`}- justify="space-between"- align="center"- gap="lg"- p="lg"- >- <DataAppSummary app={app} />-- <Group flex="0 0 auto" gap="lg" wrap="nowrap" align="center">- <DataAppStatusBadge app={app} />-- <DataAppActionsMenu app={app} canRemove={canRemove} />- </Group>- </Flex>-);diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppRepoSection/DataAppRepoSection.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppRepoSection/DataAppRepoSection.tsxdeleted file mode 100644index 94d0be4e7be..00000000000--- a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppRepoSection/DataAppRepoSection.tsx+++ /dev/null@@ -1,51 +0,0 @@-import { t } from "ttag";--import { Link } from "metabase/common/components/Link";-import { Button, Group, Icon, Stack, Text, Title } from "metabase/ui";--const REMOTE_SYNC_SETTINGS_PATH = "/admin/settings/remote-sync";--type Props = {- /** Whether a repository is connected via remote-sync. */- isConfigured: boolean;- /** The connected repository URL (shown when configured). */- url?: string | null;-};--export const DataAppRepoSection = ({ isConfigured, url }: Props) => (- <Stack gap="sm">- <Title order={3}>{t`Remote sync repo`}</Title>-- <Text>- {t`Data apps live in the repository connected via Git sync. Each app's built bundle is served at /apps/:name.`}- </Text>-- <Group gap="lg" wrap="nowrap" align="center">- <Group- gap="sm"- wrap="nowrap"- flex={1}- miw={0}- px="lg"- py="sm"- bg="background_page-secondary"- bd="1px solid var(--mb-color-border-neutral)"- bdrs="sm"- visibleFrom="sm"- >- <Icon name="git_branch" c="text-secondary" size={16} flex="0 0 auto" />- <Text- ff="monospace"- c={isConfigured ? "text-primary" : "text-secondary"}- truncate- >- {isConfigured ? url : t`No repository connected`}- </Text>- </Group>-- <Button component={Link} to={REMOTE_SYNC_SETTINGS_PATH} size="lg">- {t`Go to Git sync settings`}- </Button>- </Group>- </Stack>-);diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppSkillsSection/DataAppSkillsSection.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppSkillsSection/DataAppSkillsSection.tsxdeleted file mode 100644index 7f3a8ef4df2..00000000000--- a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppSkillsSection/DataAppSkillsSection.tsx+++ /dev/null@@ -1,27 +0,0 @@-import { t } from "ttag";--import { CopyTextArea } from "metabase/common/components/CopyTextArea";-import { Stack, Text, Title } from "metabase/ui";--// metabase/agent-skills keeps one folder per breaking version of the skill, at-// `skills/metabase-data-apps/<version>`. The skill is marked internal, so the-// install also names it.-const INSTALL_SKILL_COMMAND =- "npx skills add metabase/agent-skills/skills/metabase-data-apps/v1 \\\n --skill metabase-data-apps";--export const DataAppSkillsSection = () => (- <Stack gap="sm">- <Title order={3}>{t`AI skills`}</Title>-- {/* eslint-disable-next-line metabase/no-literal-metabase-strings -- Admin UI string */}- <Text>{t`Install the Metabase Data Apps skill in your project, then ask your AI agent to create a data app.`}</Text>-- <CopyTextArea- value={INSTALL_SKILL_COMMAND}- aria-label={t`Install command`}- autosize- // `ff` styles the field's wrapper, not the textarea that holds the text.- styles={{ input: { fontFamily: "var(--mantine-font-family-monospace)" } }}- />- </Stack>-);diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppSkillsSection/DataAppSkillsSection.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppSkillsSection/DataAppSkillsSection.unit.spec.tsxdeleted file mode 100644index 37bdb26fd60..00000000000--- a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppSkillsSection/DataAppSkillsSection.unit.spec.tsx+++ /dev/null@@ -1,37 +0,0 @@-import userEvent from "@testing-library/user-event";--import { renderWithProviders, screen, waitFor } from "__support__/ui";--import { DataAppSkillsSection } from "./DataAppSkillsSection";--const setup = () => {- renderWithProviders(<DataAppSkillsSection />);-};--const copyCommand = async () => {- const writeText = jest.fn((_text: string) => Promise.resolve());- Object.assign(navigator, { clipboard: { writeText } });-- await userEvent.click(screen.getByTestId("copy-button"));-- await waitFor(() => expect(writeText).toHaveBeenCalledTimes(1));- return writeText.mock.calls[0][0];-};--describe("DataAppSkillsSection", () => {- it("shows the command in a copy field exactly as it is copied", async () => {- setup();-- const command = await copyCommand();-- expect(screen.getByRole("textbox")).toHaveValue(command);- });-- it("installs the data apps skill from its v1 folder, naming it because it's internal", async () => {- setup();-- expect(await copyCommand()).toBe(- "npx skills add metabase/agent-skills/skills/metabase-data-apps/v1 \\\n --skill metabase-data-apps",- );- });-});diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppStatusBadge/DataAppStatusBadge.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppStatusBadge/DataAppStatusBadge.tsxdeleted file mode 100644index 60314478fae..00000000000--- a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppStatusBadge/DataAppStatusBadge.tsx+++ /dev/null@@ -1,40 +0,0 @@-import { t } from "ttag";--import { Badge, Tooltip } from "metabase/ui";-import type { DataApp } from "metabase-types/api";--import { getOutdatedDataAppMessage } from "../../../constants";--type Props = {- app: DataApp;-};--export const DataAppStatusBadge = ({ app }: Props) => (- <>- {app.outdated && (- <Tooltip label={getOutdatedDataAppMessage(app.version)}>- <Badge- size="md"- c="text-primary"- bg="background_surface-warning-strong"- bdrs="xs"- tt="none"- >- {t`Outdated`}- </Badge>- </Tooltip>- )}-- {!app.enabled && (- <Badge- size="md"- c="text-secondary"- bg="background_page-secondary"- bdrs="xs"- tt="none"- >- {t`Disabled`}- </Badge>- )}- </>-);diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppSummary/DataAppSummary.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppSummary/DataAppSummary.tsxdeleted file mode 100644index b1f4bde3ca4..00000000000--- a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppSummary/DataAppSummary.tsx+++ /dev/null@@ -1,74 +0,0 @@-import { Group, Stack, Text } from "metabase/ui";-import * as Urls from "metabase/urls";-import type { DataApp } from "metabase-types/api";--import { DataAppAllowedHosts } from "../DataAppAllowedHosts/DataAppAllowedHosts";-import { DataAppIcon } from "../DataAppIcon/DataAppIcon";--type Props = {- app: DataApp;-};--const Bullet = () => (- <Text size="sm" c="text-secondary" aria-hidden>- •- </Text>-);--export const DataAppSummary = ({ app }: Props) => {- const isOpenable = app.enabled && !app.outdated;-- return (- <Group align="center" flex="1" wrap="nowrap" miw={0}>- <DataAppIcon />-- <Stack flex="1" gap={2} miw={0}>- {isOpenable ? (- <Text- component="a"- href={Urls.getSubpathSafeUrl(Urls.dataApp(app.name))}- target="_blank"- rel="noreferrer"- fw={700}- lh="1.4"- c="core-brand"- truncate- >- {app.display_name}- </Text>- ) : (- <Text fw={700} lh="1.4" c="text-secondary" truncate>- {app.display_name}- </Text>- )}-- {app.description && (- <Text size="sm" c="text-secondary" lh="1.4" my="xxs">- {app.description}- </Text>- )}-- <Group gap="xxs" align="center" wrap="wrap">- <Text- size="sm"- c="text-secondary"- ff="monospace"- lh="1.4"- truncate- maw="100%"- >- {Urls.dataApp(app.name)}- </Text>-- {app.allowed_hosts.length > 0 && (- <>- <Bullet />-- <DataAppAllowedHosts hosts={app.allowed_hosts} />- </>- )}- </Group>- </Stack>- </Group>- );-};diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppSummary/DataAppSummary.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppSummary/DataAppSummary.unit.spec.tsxdeleted file mode 100644index 21dd234cdad..00000000000--- a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppSummary/DataAppSummary.unit.spec.tsx+++ /dev/null@@ -1,78 +0,0 @@-import { renderWithProviders, screen } from "__support__/ui";-import { createMockDataApp } from "metabase-types/api/mocks";--import { DataAppSummary } from "./DataAppSummary";--describe("DataAppSummary", () => {- it("renders an enabled app's name as a link to the app", () => {- renderWithProviders(- <DataAppSummary- app={createMockDataApp({ name: "sales", display_name: "Sales" })}- />,- );-- const link = screen.getByRole("link", { name: "Sales" });- expect(link).toHaveAttribute(- "href",- expect.stringContaining("/apps/sales"),- );- });-- it("renders a disabled app's name as plain text (no link)", () => {- renderWithProviders(- <DataAppSummary- app={createMockDataApp({ display_name: "Sales", enabled: false })}- />,- );-- expect(screen.getByText("Sales")).toBeInTheDocument();- expect(- screen.queryByRole("link", { name: "Sales" }),- ).not.toBeInTheDocument();- });-- it("renders an outdated app's name as plain text (it refuses to open)", () => {- renderWithProviders(- <DataAppSummary- app={createMockDataApp({- display_name: "Sales",- enabled: true,- outdated: true,- })}- />,- );-- expect(screen.getByText("Sales")).toBeInTheDocument();- expect(- screen.queryByRole("link", { name: "Sales" }),- ).not.toBeInTheDocument();- });-- describe("description", () => {- it("renders the description when the app declares one", () => {- renderWithProviders(- <DataAppSummary- app={createMockDataApp({- display_name: "Sales",- description: "Pipeline health by region",- })}- />,- );-- expect(screen.getByText("Pipeline health by region")).toBeInTheDocument();- });-- it("renders nothing extra when the app has no description", () => {- renderWithProviders(- <DataAppSummary- app={createMockDataApp({ display_name: "Sales", description: null })}- />,- );-- expect(screen.getByText("Sales")).toBeInTheDocument();- expect(- screen.queryByText("Pipeline health by region"),- ).not.toBeInTheDocument();- });- });-});diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppsEmptyState/DataAppsEmptyState.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppsEmptyState/DataAppsEmptyState.tsxdeleted file mode 100644index 95a084e919c..00000000000--- a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppsEmptyState/DataAppsEmptyState.tsx+++ /dev/null@@ -1,29 +0,0 @@-import { t } from "ttag";--import { Flex, Icon, Text } from "metabase/ui";--export const DataAppsEmptyState = () => (- <Flex- direction="column"- align="center"- justify="center"- gap="lg"- bd="1px solid var(--mb-color-border-neutral)"- bdrs="sm"- bg="background_page-primary"- mih="16rem"- p="xxl"- >- <Flex- align="center"- justify="center"- w="6rem"- h="6rem"- bg="background_page-secondary"- style={{ borderRadius: "50%" }}- >- <Icon name="app" size={48} c="border-neutral" />- </Flex>- <Text c="text-disabled">{t`Your data apps will appear here`}</Text>- </Flex>-);diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppsPromoBanner/DataAppsBanner.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppsPromoBanner/DataAppsBanner.tsxdeleted file mode 100644index 13a1c1c2611..00000000000--- a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppsPromoBanner/DataAppsBanner.tsx+++ /dev/null@@ -1,45 +0,0 @@-import { t } from "ttag";--import { UserHasSeen } from "metabase/common/components/UserHasSeen/UserHasSeen";-import { ActionIcon, Box, Group, Icon, Stack, Text } from "metabase/ui";--const BANNER_ID = "data-apps-admin-settings-banner";--export const DataAppsBanner = () => (- <UserHasSeen id={BANNER_ID}>- {({ hasSeen, ack }) =>- hasSeen ? null : (- <Box- pos="relative"- p="xl"- bg="background_surface-brand-subtle"- bd="1px solid var(--mb-color-border-neutral)"- bdrs="sm"- >- <ActionIcon- pos="absolute"- top="1rem"- right="1rem"- variant="subtle"- aria-label={t`Dismiss`}- onClick={ack}- >- <Icon name="close" />- </ActionIcon>-- <Stack gap="sm">- <Group gap="sm" wrap="nowrap" pr="xxl">- <Icon name="app" c="core-brand" flex="0 0 auto" />- <Text fw={700} c="core-brand">- {t`AI-generated React apps on top of your semantic layer`}- </Text>- </Group>-- {/* eslint-disable-next-line metabase/no-literal-metabase-strings -- Admin UI string */}- <Text>{t`Have your AI agent of choice use Metabase's Data App skills to build a custom app backed by git, using the vetted metrics and data you've defined within Metabase.`}</Text>- </Stack>- </Box>- )- }- </UserHasSeen>-);diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/tests/ManageDataAppGroupsPage.setup.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/tests/ManageDataAppGroupsPage.setup.tsxdeleted file mode 100644index b20ab37af31..00000000000--- a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/tests/ManageDataAppGroupsPage.setup.tsx+++ /dev/null@@ -1,138 +0,0 @@-import userEvent from "@testing-library/user-event";-import fetchMock from "fetch-mock";--import { renderWithProviders, screen, waitFor } from "__support__/ui";-import { UndoListing } from "metabase/common/components/UndoListing";-import { Route } from "metabase/router";-import type {- DataApp,- DataAppGroup,- DataAppGroupPermissionWarning,-} from "metabase-types/api";-import { createMockDataApp, createMockGroup } from "metabase-types/api/mocks";--import { ManageDataAppGroupsPage } from "../ManageDataAppGroupsPage";--export const FINCHES_GROUP_ID = 3;-export const OWLS_GROUP_ID = 4;--const candidates = [- createMockGroup({- id: 1,- name: "All Users",- magic_group_type: "all-internal-users",- }),-- createMockGroup({- id: 2,- name: "Administrators",- magic_group_type: "admin",- }),-- createMockGroup({ id: FINCHES_GROUP_ID, name: "Finches" }),- createMockGroup({ id: OWLS_GROUP_ID, name: "Owls" }),-- createMockGroup({- id: 5,- name: "Tenant",- is_tenant_group: true,- }),-];--export const setup = ({- app = createMockDataApp(),- groups = [],-- failFirstAdd = false,-- warnings = [],- warningsError = false,- warningsResponse,-}: {- app?: DataApp;- groups?: DataAppGroup[];-- failFirstAdd?: boolean;-- warnings?: DataAppGroupPermissionWarning[];- warningsError?: boolean;- warningsResponse?: Promise<DataAppGroupPermissionWarning[]>;-} = {}) => {- let assigned = [...groups];-- fetchMock.get("path:/api/ee/apps", [app]);- fetchMock.get("path:/api/permissions/group", candidates);- fetchMock.get("path:/api/ee/apps/sales/groups", () => assigned);-- fetchMock.get(- "path:/api/ee/apps/sales",- !app.enabled ? 404 : !app.resource_collection_id ? 409 : app,- );-- fetchMock.get(- "path:/api/ee/apps/sales/group-permission-warnings",- () =>- warningsResponse ??- (warningsError- ? 500- : warnings.filter((warning) =>- assigned.some((group) => group.id === warning.group_id),- )),- { name: "data-app-group-permission-warnings" },- );-- fetchMock.post("path:/api/ee/apps/sales/groups", ({ options: { body } }) => {- if (failFirstAdd) {- failFirstAdd = false;- return 500;- }-- const { group_ids } = JSON.parse(String(body));-- assigned = [- ...assigned,- ...candidates- .filter((group) => group_ids.includes(group.id))- .map((group) => ({ ...group, member_count: 0 })),- ];-- return assigned;- });-- fetchMock.delete("express:/api/ee/apps/sales/groups/:id", ({ url }) => {- // `/api/ee/apps/sales/groups/5` -> `5`- const groupId = Number(url.split("/").pop());- assigned = assigned.filter((group) => group.id !== groupId);-- return 204;- });-- renderWithProviders(- <Route- path="admin/settings/apps/:slug/groups"- element={- <>- <ManageDataAppGroupsPage />- <UndoListing />- </>- }- />,- { withRouter: true, initialRoute: "/admin/settings/apps/sales/groups" },- );-};--export async function openGroupAssignmentPicker() {- await userEvent.click(- await screen.findByRole("button", { name: "Add groups" }),- );-- await waitFor(() =>- expect(- screen.getByRole("textbox", { name: "Search for groups to add" }),- ).toBeEnabled(),- );-- await userEvent.click(- screen.getByRole("textbox", { name: "Search for groups to add" }),- );-}diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/index.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/index.tsxdeleted file mode 100644index 6464b8a1e9b..00000000000--- a/enterprise/frontend/src/metabase-enterprise/data_apps/index.tsx+++ /dev/null@@ -1,25 +0,0 @@-import { PLUGIN_DATA_APPS } from "metabase/plugins";-import { hasPremiumFeature } from "metabase-enterprise/settings";--import { ManageDataAppGroupsPage } from "./admin/ManageDataAppGroupsPage";-import { ManageDataAppsPage } from "./admin/ManageDataAppsPage";-import { DataAppsNavbarSection } from "./navbar/DataAppsNavbarSection";-import { getRoutes, registerDataAppsPagePrefetch } from "./routes";--/**- * Initialize data-apps plugin features.- *- * The admin nav item + the upsell live in OSS (so they show on every edition);- * the EE plugin only provides the real management UI, gated on the `data-apps`- * token feature.- */-export function initializePlugin() {- if (hasPremiumFeature("data-apps")) {- PLUGIN_DATA_APPS.isEnabled = true;- PLUGIN_DATA_APPS.getRoutes = getRoutes;- PLUGIN_DATA_APPS.ManageDataAppsPage = ManageDataAppsPage;- PLUGIN_DATA_APPS.ManageDataAppGroupsPage = ManageDataAppGroupsPage;- PLUGIN_DATA_APPS.MainNavbarSection = DataAppsNavbarSection;- registerDataAppsPagePrefetch();- }-}diff --git a/enterprise/frontend/src/metabase-enterprise/lazy-plugin-routes.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/lazy-plugin-routes.unit.spec.tsxindex 91c98dd7229..a450ce44748 100644--- a/enterprise/frontend/src/metabase-enterprise/lazy-plugin-routes.unit.spec.tsx+++ b/enterprise/frontend/src/metabase-enterprise/lazy-plugin-routes.unit.spec.tsx@@ -7,7 +7,7 @@ import {getMcpToolsAccessRoutes,} from "metabase-enterprise/ai-controls/routes";import getApplicationPermissionsRoutes from "metabase-enterprise/application_permissions/routes";-import { getRoutes as getDataAppRoutes } from "metabase-enterprise/data_apps/routes";+import { getRoutes as getDataAppRoutes } from "metabase-enterprise/data-apps/host/routes";import { getDataStudioDependencyRoutes } from "metabase-enterprise/dependencies/routes";import { getTransformToolsRoutes } from "metabase-enterprise/replacement/routes";import { getDataStudioSchemaViewerRoutes } from "metabase-enterprise/schema_viewer/routes";diff --git a/enterprise/frontend/src/metabase-enterprise/plugins.ts b/enterprise/frontend/src/metabase-enterprise/plugins.tsindex 6785dfabe48..1d0b5516de2 100644--- a/enterprise/frontend/src/metabase-enterprise/plugins.ts+++ b/enterprise/frontend/src/metabase-enterprise/plugins.ts@@ -18,8 +18,8 @@ import { initializePlugin as initializeCollections } from "./collections";import { initializePlugin as initializeContentTranslation } from "./content_translation";import { initializePlugin as initializeContentVerification } from "./content_verification";import { initializePlugin as initializeCustomViz } from "./custom_viz";+import { initializePlugin as initializeDataApps } from "./data-apps";import { initializePlugin as initializeLibrary } from "./data-studio/library";-import { initializePlugin as initializeDataApps } from "./data_apps";import { initializePlugin as initializeDatabaseReplication } from "./database_replication";import { initializePlugin as initializeDatabaseRouting } from "./database_routing";import { initializePlugin as initializeDependencies } from "./dependencies";@@ -54,6 +54,7 @@ import { initializePlugin as initializeTenants } from "./tenants";import { initializePlugin as initializeTransforms } from "./transforms";import { initializePlugin as initializeTransformsInspector } from "./transforms-inspector";import { initializePlugin as initializeTransformsPython } from "./transforms-python";+import { initializePlugin as initializeTransformsTesting } from "./transforms-testing";import { initializePlugin as initializeUploadManagement } from "./upload_management";import { initializePlugin as initializeUserProvisioning } from "./user_provisioning";import { initializePlugin as initializeWhitelabel } from "./whitelabel";@@ -111,6 +112,7 @@ export function initializePlugins() {initializeTools();initializeTransforms();initializeTransformsInspector();+ initializeTransformsTesting();initializeTransformsPython();initializeUploadManagement();initializeUserProvisioning();diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/ChangesLists/AllChangesView.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/ChangesLists/AllChangesView.unit.spec.tsxindex 38563bdb7db..f5ed54f3abf 100644--- a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/ChangesLists/AllChangesView.unit.spec.tsx+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/ChangesLists/AllChangesView.unit.spec.tsx@@ -1135,7 +1135,7 @@ describe("AllChangesView", () => {expect(await screen.findByRole("link", { name: "Data apps" }),- ).toHaveAttribute("href", "/admin/settings/apps");+ ).toHaveAttribute("href", "/data-studio/apps");expect(screen.getByText("Root")).toBeInTheDocument();expect(screen.getByRole("link", { name: /boba-staff-review/ }),diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/displayGroups.ts b/enterprise/frontend/src/metabase-enterprise/remote_sync/displayGroups.tsindex 9d93302aeb1..47e56976c65 100644--- a/enterprise/frontend/src/metabase-enterprise/remote_sync/displayGroups.ts+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/displayGroups.ts@@ -2,7 +2,7 @@ import { t } from "ttag";import _ from "underscore";import { isLibraryCollection } from "metabase/common/collections/utils";-import { dataAppsSettings, transformList } from "metabase/urls";+import { dataStudioDataApps, transformList } from "metabase/urls";import type {Collection,CollectionId,@@ -109,7 +109,7 @@ const displayGroupSpecs: DisplayGroupSpec[] = [virtualRoot: {id: DATA_APPS_ROOT_ID,name: () => t`Data apps`,- url: dataAppsSettings,+ url: dataStudioDataApps,},icon: "app",priority: 70,diff --git a/enterprise/frontend/src/metabase-enterprise/replacement/pages/MigrateModelsPage/ModelSidebar/ModelSidebar.tsx b/enterprise/frontend/src/metabase-enterprise/replacement/pages/MigrateModelsPage/ModelSidebar/ModelSidebar.tsxindex d19f6d1702f..dd277f63828 100644--- a/enterprise/frontend/src/metabase-enterprise/replacement/pages/MigrateModelsPage/ModelSidebar/ModelSidebar.tsx+++ b/enterprise/frontend/src/metabase-enterprise/replacement/pages/MigrateModelsPage/ModelSidebar/ModelSidebar.tsx@@ -2,6 +2,7 @@ import { memo } from "react";import { skipToken, useGetCardQuery, useGetDatabaseQuery } from "metabase/api";import { DelayedLoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper/DelayedLoadingAndErrorWrapper";+import { SidebarResizableBox } from "metabase/common/components/SidebarResizableBox";import { Box, Center, Stack } from "metabase/ui";import type { CardId } from "metabase-types/api";@@ -11,7 +12,6 @@ import { InfoSection } from "./InfoSection";import { LocationSection } from "./LocationSection";import S from "./ModelSidebar.module.css";import { SidebarHeader } from "./SidebarHeader";-import { SidebarResizableBox } from "./SidebarResizableBox";type ModelSidebarProps = {cardId: CardId;diff --git a/enterprise/frontend/src/metabase-enterprise/replacement/pages/MigrateModelsPage/ModelSidebar/SidebarResizableBox/index.ts b/enterprise/frontend/src/metabase-enterprise/replacement/pages/MigrateModelsPage/ModelSidebar/SidebarResizableBox/index.tsdeleted file mode 100644index cdad874b262..00000000000--- a/enterprise/frontend/src/metabase-enterprise/replacement/pages/MigrateModelsPage/ModelSidebar/SidebarResizableBox/index.ts+++ /dev/null@@ -1 +0,0 @@-export * from "./SidebarResizableBox";diff --git a/enterprise/frontend/src/metabase-enterprise/transforms-testing/components/TransformTestDataCard/TransformTestDataCard.tsx b/enterprise/frontend/src/metabase-enterprise/transforms-testing/components/TransformTestDataCard/TransformTestDataCard.tsxnew file mode 100644index 00000000000..8698473015c--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/transforms-testing/components/TransformTestDataCard/TransformTestDataCard.tsx@@ -0,0 +1,97 @@+import { useMemo } from "react";+import { t } from "ttag";++import { CodeEditor } from "metabase/common/components/CodeEditor";+import type { TreeTableColumnDef } from "metabase/ui";+import {+ Box,+ Card,+ Divider,+ Ellipsified,+ Group,+ Icon,+ Text,+ TreeTable,+ useTreeTableInstance,+} from "metabase/ui";+import type {+ IconName,+ TransformTestData,+ TransformTestRow,+ TransformTestRowValue,+ TransformTestRowsData,+} from "metabase-types/api";++type TransformTestDataCardProps = {+ name: string;+ icon: IconName;+ description: string;+ data: TransformTestData;+};++export function TransformTestDataCard({+ name,+ icon,+ description,+ data,+}: TransformTestDataCardProps) {+ return (+ <Card withBorder p={0} aria-label={name}>+ <Group gap="sm" px="lg" py="md" wrap="nowrap">+ <Icon name={icon} c="core-brand" />+ <Text fw="bold">{name}</Text>+ <Text c="text-secondary" ml="auto">+ {description}+ </Text>+ </Group>+ <Divider />+ {data.format === "rows" ? (+ <RowsTable name={name} data={data} />+ ) : (+ <Box bg="background_page-secondary" py="sm">+ <CodeEditor value={data.sql} language="sql" readOnly />+ </Box>+ )}+ </Card>+ );+}++type RowEntry = {+ id: string;+ row: TransformTestRow;+};++type RowsTableProps = {+ name: string;+ data: TransformTestRowsData;+};++function RowsTable({ name, data }: RowsTableProps) {+ const entries = useMemo(+ () => data.rows.map((row, index) => ({ id: String(index), row })),+ [data.rows],+ );+ const columns = useMemo(+ (): TreeTableColumnDef<RowEntry>[] =>+ data.columns.map((column) => ({+ id: column.name,+ header: column.name,+ accessorFn: (entry) => formatValue(entry.row[column.name]),+ minWidth: 80,+ cell: ({ getValue }) => <Ellipsified>{String(getValue())}</Ellipsified>,+ })),+ [data.columns],+ );++ const instance = useTreeTableInstance({+ data: entries,+ columns,+ getNodeId: (entry) => entry.id,+ });++ return <TreeTable instance={instance} ariaLabel={t`Rows of ${name}`} />;+}++function formatValue(value: TransformTestRowValue | undefined): string {+ return value === undefined ? "" : String(value);+}diff --git a/enterprise/frontend/src/metabase-enterprise/transforms-testing/components/TransformTestDataCard/index.ts b/enterprise/frontend/src/metabase-enterprise/transforms-testing/components/TransformTestDataCard/index.tsnew file mode 100644index 00000000000..dd08f19c048--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/transforms-testing/components/TransformTestDataCard/index.ts@@ -0,0 +1 @@+export { TransformTestDataCard } from "./TransformTestDataCard";diff --git a/enterprise/frontend/src/metabase-enterprise/transforms-testing/components/TransformTestHeader/TransformTestHeader.tsx b/enterprise/frontend/src/metabase-enterprise/transforms-testing/components/TransformTestHeader/TransformTestHeader.tsxnew file mode 100644index 00000000000..e788f7cded6--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/transforms-testing/components/TransformTestHeader/TransformTestHeader.tsx@@ -0,0 +1,69 @@+import { t } from "ttag";++import { Link } from "metabase/common/components/Link";+import {+ type PillTab,+ PillTabNavigation,+} from "metabase/common/components/PillTabNavigation";+import { DataStudioBreadcrumbs } from "metabase/common/data-studio/components/DataStudioBreadcrumbs";+import {+ PaneHeader,+ PanelHeaderTitle,+} from "metabase/common/data-studio/components/PaneHeader";+import { useCollectionPath } from "metabase/common/data-studio/hooks/use-collection-path/useCollectionPath";+import * as Urls from "metabase/urls";+import type { Transform, TransformTest } from "metabase-types/api";++type TransformTestHeaderProps = {+ transform: Transform;+ test: TransformTest;+};++export function TransformTestHeader({+ transform,+ test,+}: TransformTestHeaderProps) {+ const { path, isLoadingPath } = useCollectionPath({+ collectionId: transform.collection_id,+ namespace: "transforms",+ });++ const runsUrl = Urls.transformTestRuns(transform.id, test.id);+ const tabs: PillTab[] = [+ {+ label: t`Overview`,+ to: Urls.transformTest(transform.id, test.id),+ },+ {+ label: t`Runs`,+ to: runsUrl,+ isSelected: (pathname: string) => pathname.startsWith(runsUrl),+ },+ ];++ return (+ <PaneHeader+ title={<PanelHeaderTitle>{test.name}</PanelHeaderTitle>}+ icon="test_tube"+ tabs={<PillTabNavigation tabs={tabs} />}+ breadcrumbs={+ <DataStudioBreadcrumbs loading={isLoadingPath}>+ <Link to={Urls.transformList()}>{t`Data transformation`}</Link>+ {path?.map((folder) => (+ <Link+ key={folder.id}+ to={`${Urls.transformList()}?collectionId=${folder.id}`}+ >+ {folder.name}+ </Link>+ ))}+ <Link to={Urls.transformTestList(transform.id)}>+ {transform.name}+ </Link>+ {test.name}+ </DataStudioBreadcrumbs>+ }+ data-testid="transform-test-header"+ />+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/transforms-testing/components/TransformTestHeader/index.ts b/enterprise/frontend/src/metabase-enterprise/transforms-testing/components/TransformTestHeader/index.tsnew file mode 100644index 00000000000..58abed2c2f7--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/transforms-testing/components/TransformTestHeader/index.ts@@ -0,0 +1 @@+export { TransformTestHeader } from "./TransformTestHeader";diff --git a/enterprise/frontend/src/metabase-enterprise/transforms-testing/components/TransformTestRunButton/TransformTestRunButton.tsx b/enterprise/frontend/src/metabase-enterprise/transforms-testing/components/TransformTestRunButton/TransformTestRunButton.tsxnew file mode 100644index 00000000000..b1a156631d8--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/transforms-testing/components/TransformTestRunButton/TransformTestRunButton.tsx@@ -0,0 +1,42 @@+import { useMemo } from "react";+import { t } from "ttag";++import { useMetadataToasts } from "metabase/common/hooks";+import { RunButton } from "metabase/transforms/components/RunButton";+import { useRunTransformTestMutation } from "metabase-enterprise/api";+import type { TransformTest } from "metabase-types/api";++import { getRunStatusInfo, getRunTransformTestCacheKey } from "../../utils";++type TransformTestRunButtonProps = {+ test: TransformTest;+ readOnly: boolean;+};++export function TransformTestRunButton({+ test,+ readOnly,+}: TransformTestRunButtonProps) {+ const [runTest, { isLoading }] = useRunTransformTestMutation({+ fixedCacheKey: getRunTransformTestCacheKey(test.id),+ });+ const run = useMemo(() => getRunStatusInfo(test.last_run), [test.last_run]);+ const { sendErrorToast } = useMetadataToasts();++ const handleRun = async () => {+ const { error } = await runTest(test.id);+ if (error) {+ sendErrorToast(t`Failed to run the test`);+ }+ };++ return (+ <RunButton+ id={test.id}+ run={run}+ isLoading={isLoading}+ isDisabled={readOnly}+ onRun={handleRun}+ />+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/transforms-testing/components/TransformTestRunButton/index.ts b/enterprise/frontend/src/metabase-enterprise/transforms-testing/components/TransformTestRunButton/index.tsnew file mode 100644index 00000000000..d273c2384e3--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/transforms-testing/components/TransformTestRunButton/index.ts@@ -0,0 +1 @@+export { TransformTestRunButton } from "./TransformTestRunButton";diff --git a/enterprise/frontend/src/metabase-enterprise/transforms-testing/components/TransformTestSection/TransformTestSection.tsx b/enterprise/frontend/src/metabase-enterprise/transforms-testing/components/TransformTestSection/TransformTestSection.tsxnew file mode 100644index 00000000000..7408447e19d--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/transforms-testing/components/TransformTestSection/TransformTestSection.tsx@@ -0,0 +1,25 @@+import type { ReactNode } from "react";++import { Stack, Text, Title } from "metabase/ui";++type TransformTestSectionProps = {+ label: string;+ description: string;+ children: ReactNode;+};++export function TransformTestSection({+ label,+ description,+ children,+}: TransformTestSectionProps) {+ return (+ <Stack component="section" aria-label={label}>+ <Stack gap="sm">+ <Title order={4}>{label}</Title>+ <Text c="text-secondary">{description}</Text>+ </Stack>+ <Stack gap="md">{children}</Stack>+ </Stack>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/transforms-testing/components/TransformTestSection/index.ts b/enterprise/frontend/src/metabase-enterprise/transforms-testing/components/TransformTestSection/index.tsnew file mode 100644index 00000000000..6e0cba80e29--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/transforms-testing/components/TransformTestSection/index.ts@@ -0,0 +1 @@+export { TransformTestSection } from "./TransformTestSection";diff --git a/enterprise/frontend/src/metabase-enterprise/transforms-testing/constants.ts b/enterprise/frontend/src/metabase-enterprise/transforms-testing/constants.tsnew file mode 100644index 00000000000..0b808a146e6--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/transforms-testing/constants.ts@@ -0,0 +1,3 @@+export const MB_CLI_NAME = "mb";++export const PAGE_SIZE = 25;diff --git a/enterprise/frontend/src/metabase-enterprise/transforms-testing/hooks/use-route-transform-test/index.ts b/enterprise/frontend/src/metabase-enterprise/transforms-testing/hooks/use-route-transform-test/index.tsnew file mode 100644index 00000000000..590377e7cf9--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/transforms-testing/hooks/use-route-transform-test/index.ts@@ -0,0 +1 @@+export { useRouteTransformTest } from "./use-route-transform-test";diff --git a/enterprise/frontend/src/metabase-enterprise/transforms-testing/hooks/use-route-transform-test/use-route-transform-test.ts b/enterprise/frontend/src/metabase-enterprise/transforms-testing/hooks/use-route-transform-test/use-route-transform-test.tsnew file mode 100644index 00000000000..89ca78b1fd3--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/transforms-testing/hooks/use-route-transform-test/use-route-transform-test.ts@@ -0,0 +1,36 @@+import { skipToken, useGetTransformQuery } from "metabase/api";+import { useParams } from "metabase/router";+import { useTransformPermissions } from "metabase/transforms/hooks/use-transform-permissions";+import * as Urls from "metabase/urls";+import { useGetTransformTestQuery } from "metabase-enterprise/api";++type TransformTestRouteParams = {+ transformId: string;+ testId: string;+};++export function useRouteTransformTest() {+ const params = useParams<TransformTestRouteParams>();+ const transformId = Urls.extractEntityId(params.transformId);+ const testId = Urls.extractEntityId(params.testId);+ const {+ data: transform,+ isLoading: isLoadingTransform,+ error: transformError,+ } = useGetTransformQuery(transformId ?? skipToken);+ const {+ data: test,+ isLoading: isLoadingTest,+ error: testError,+ } = useGetTransformTestQuery(testId ?? skipToken);+ const { readOnly, isLoadingDatabases, databasesError } =+ useTransformPermissions({ transform });++ return {+ transform,+ test,+ readOnly: readOnly ?? false,+ isLoading: isLoadingTransform || isLoadingTest || isLoadingDatabases,+ error: transformError ?? testError ?? databasesError,+ };+}diff --git a/enterprise/frontend/src/metabase-enterprise/transforms-testing/index.ts b/enterprise/frontend/src/metabase-enterprise/transforms-testing/index.tsnew file mode 100644index 00000000000..8416a332c5f--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/transforms-testing/index.ts@@ -0,0 +1,11 @@+import { PLUGIN_TRANSFORMS_TESTING } from "metabase/plugins";+import { hasPremiumFeature } from "metabase-enterprise/settings";++import { getTransformTestRoutes } from "./routes";++export function initializePlugin() {+ if (hasPremiumFeature("transforms-testing")) {+ PLUGIN_TRANSFORMS_TESTING.isEnabled = true;+ PLUGIN_TRANSFORMS_TESTING.getTransformTestRoutes = getTransformTestRoutes;+ }+}diff --git a/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestListPage/TransformTestList/TransformTestList.tsx b/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestListPage/TransformTestList/TransformTestList.tsxnew file mode 100644index 00000000000..8c4814de2fd--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestListPage/TransformTestList/TransformTestList.tsx@@ -0,0 +1,181 @@+import type { Row } from "@tanstack/react-table";+import { type MouseEvent, useCallback, useMemo, useState } from "react";+import { jt, t } from "ttag";++import { DateTime } from "metabase/common/components/DateTime";+import { ForwardRefLink } from "metabase/common/components/Link";+import { ListEmptyState } from "metabase/common/components/ListEmptyState";+import { MoreMenuButton } from "metabase/common/data-studio/components/MoreMenuButton";+import { useMetadataToasts } from "metabase/common/hooks";+import { useNavigate } from "metabase/router";+import type { TreeTableColumnDef } from "metabase/ui";+import {+ Card,+ Code,+ Ellipsified,+ Icon,+ Menu,+ Stack,+ TextInput,+ TreeTable,+ useTreeTableInstance,+} from "metabase/ui";+import * as Urls from "metabase/urls";+import { useRunTransformTestMutation } from "metabase-enterprise/api";+import type { TransformTest, TransformTestRun } from "metabase-types/api";++import { MB_CLI_NAME } from "../../../constants";+import { isFailedTestRunStatus } from "../../../utils";++type TransformTestListProps = {+ tests: TransformTest[];+ readOnly: boolean;+};++export function TransformTestList({ tests, readOnly }: TransformTestListProps) {+ const navigate = useNavigate();+ const [searchQuery, setSearchQuery] = useState("");+ const columns = useMemo(() => getColumns(readOnly), [readOnly]);++ const handleRowActivate = useCallback(+ (row: Row<TransformTest>) => {+ navigate(Urls.transformTest(row.original.transform_id, row.original.id));+ },+ [navigate],+ );++ const treeTableInstance = useTreeTableInstance({+ data: tests,+ columns,+ getNodeId: (test) => String(test.id),+ globalFilter: searchQuery,+ onGlobalFilterChange: setSearchQuery,+ onRowActivate: handleRowActivate,+ });++ return (+ <Stack>+ <TextInput+ placeholder={t`Search...`}+ leftSection={<Icon name="search" />}+ bdrs="sm"+ value={searchQuery}+ onChange={(event) => setSearchQuery(event.target.value)}+ />+ <Card withBorder p={0}>+ <TreeTable+ instance={treeTableInstance}+ emptyState={+ searchQuery ? (+ <ListEmptyState label={t`No tests found`} />+ ) : (+ <ListEmptyState+ label={t`No tests yet`}+ description={jt`Create tests with the ${(+ <Code key="mb">{MB_CLI_NAME}</Code>+ )} CLI or with remote sync.`}+ />+ )+ }+ ariaLabel={t`Transform tests`}+ onRowClick={handleRowActivate}+ />+ </Card>+ </Stack>+ );+}++function getColumns(readOnly: boolean): TreeTableColumnDef<TransformTest>[] {+ const columns: TreeTableColumnDef<TransformTest>[] = [+ {+ id: "name",+ accessorKey: "name",+ header: t`Name`,+ minWidth: 120,+ cell: ({ row }) => <Ellipsified>{row.original.name}</Ellipsified>,+ },+ {+ id: "checks",+ accessorFn: (test) => test.expectations.length,+ header: t`Checks`,+ width: 120,+ cell: ({ row }) => row.original.expectations.length,+ },+ {+ id: "last_run",+ accessorFn: (test) => test.last_run?.start_time,+ header: t`Last Run`,+ minWidth: 120,+ cell: ({ row }) =>+ row.original.last_run ? (+ <LastRunCell run={row.original.last_run} />+ ) : null,+ },+ ];++ if (readOnly) {+ return columns;+ }++ return [+ ...columns,+ {+ id: "actions",+ header: "",+ width: 48,+ cell: ({ row }) => <TransformTestMenu test={row.original} />,+ },+ ];+}++function LastRunCell({ run }: { run: TransformTestRun }) {+ return (+ <Ellipsified>+ {isFailedTestRunStatus(run.status) ? t`Failed` : t`Last run`}{" "}+ <DateTime value={run.start_time} />+ </Ellipsified>+ );+}++function TransformTestMenu({ test }: { test: TransformTest }) {+ const [runTest] = useRunTransformTestMutation();+ const { sendErrorToast, sendSuccessToast } = useMetadataToasts();++ const handleRun = async () => {+ const { data, error } = await runTest(test.id);+ if (error || data == null) {+ sendErrorToast(t`Failed to run the test`);+ } else if (data.status === "passed") {+ sendSuccessToast(t`Test passed`);+ } else {+ sendErrorToast(t`Test failed`);+ }+ };++ const stopPropagation = (event: MouseEvent) => {+ event.stopPropagation();+ };++ return (+ <Menu>+ <Menu.Target>+ <MoreMenuButton+ aria-label={t`Test options`}+ onClick={stopPropagation}+ />+ </Menu.Target>+ <Menu.Dropdown onClick={stopPropagation}>+ <Menu.Item leftSection={<Icon name="play" />} onClick={handleRun}>+ {t`Run test`}+ </Menu.Item>+ <Menu.Item+ component={ForwardRefLink}+ to={Urls.transformTestRuns(test.transform_id, test.id)}+ leftSection={<Icon name="clock" />}+ >+ {t`View runs`}+ </Menu.Item>+ </Menu.Dropdown>+ </Menu>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestListPage/TransformTestList/index.ts b/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestListPage/TransformTestList/index.tsnew file mode 100644index 00000000000..79e2e237361--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestListPage/TransformTestList/index.ts@@ -0,0 +1 @@+export { TransformTestList } from "./TransformTestList";diff --git a/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestListPage/TransformTestListPage.tsx b/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestListPage/TransformTestListPage.tsxnew file mode 100644index 00000000000..1c349ae6ac0--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestListPage/TransformTestListPage.tsx@@ -0,0 +1,51 @@+import { skipToken, useGetTransformQuery } from "metabase/api";+import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";+import { PageContainer } from "metabase/common/data-studio/components/PageContainer";+import { useParams } from "metabase/router";+import { TransformHeader } from "metabase/transforms/components/TransformHeader";+import { useTransformPermissions } from "metabase/transforms/hooks/use-transform-permissions";+import { Center } from "metabase/ui";+import * as Urls from "metabase/urls";+import { useListTransformTestsQuery } from "metabase-enterprise/api";++import { TransformTestList } from "./TransformTestList";++type TransformTestListPageParams = {+ transformId: string;+};++export function TransformTestListPage() {+ const params = useParams<TransformTestListPageParams>();+ const transformId = Urls.extractEntityId(params.transformId);+ const {+ data: transform,+ isLoading: isLoadingTransform,+ error: transformError,+ } = useGetTransformQuery(transformId ?? skipToken);+ const {+ data: tests = [],+ isLoading: isLoadingTests,+ error: testsError,+ } = useListTransformTestsQuery(+ transformId != null ? { "transform-id": transformId } : skipToken,+ );+ const { readOnly, isLoadingDatabases, databasesError } =+ useTransformPermissions({ transform });+ const isLoading = isLoadingTransform || isLoadingTests || isLoadingDatabases;+ const error = transformError ?? testsError ?? databasesError;++ if (transform == null || isLoading || error != null) {+ return (+ <Center h="100%">+ <LoadingAndErrorWrapper loading={isLoading} error={error} />+ </Center>+ );+ }++ return (+ <PageContainer data-testid="transform-test-list">+ <TransformHeader transform={transform} readOnly={readOnly} />+ <TransformTestList tests={tests} readOnly={readOnly ?? false} />+ </PageContainer>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestListPage/TransformTestListPage.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestListPage/TransformTestListPage.unit.spec.tsxnew file mode 100644index 00000000000..62816543718--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestListPage/TransformTestListPage.unit.spec.tsx@@ -0,0 +1,231 @@+import userEvent from "@testing-library/user-event";+import fetchMock from "fetch-mock";++import { setupEnterpriseOnlyPlugin } from "__support__/enterprise";+import {+ setupCollectionByIdEndpoint,+ setupDatabasesEndpoints,+ setupGetTransformEndpoint,+ setupListTransformTestsEndpoint,+ setupRunTransformTestEndpoint,+ setupUserMetabotPermissionsEndpoint,+ setupUsersEndpoints,+} from "__support__/server-mocks";+import { mockSettings } from "__support__/settings";+import { createMockState } from "__support__/state";+import {+ mockGetBoundingClientRect,+ renderWithProviders,+ screen,+ waitFor,+ within,+} from "__support__/ui";+import { Route } from "metabase/router";+import * as Urls from "metabase/urls";+import type { Transform, TransformTest } from "metabase-types/api";+import {+ createMockCollection,+ createMockDatabase,+ createMockTokenFeatures,+ createMockTransform,+ createMockTransformTest,+ createMockTransformTestEmptyExpectation,+ createMockTransformTestEqualsExpectation,+ createMockTransformTestRun,+} from "metabase-types/api/mocks";++import { TransformTestListPage } from "./TransformTestListPage";++type SetupOpts = {+ transform?: Transform;+ tests?: TransformTest[];+ canWrite?: boolean;+};++function setup({+ transform = createMockTransform({ id: 1, name: "Customer revenue" }),+ tests = [],+ canWrite = true,+}: SetupOpts = {}) {+ mockGetBoundingClientRect({ width: 1000, height: 600 });+ setupDatabasesEndpoints([+ createMockDatabase({+ id: 1,+ transforms_permissions: canWrite ? "write" : "none",+ }),+ ]);+ setupCollectionByIdEndpoint({+ collections: [createMockCollection({ id: "root" })],+ });+ setupUserMetabotPermissionsEndpoint();+ setupUsersEndpoints([]);+ setupGetTransformEndpoint(transform);+ setupListTransformTestsEndpoint(tests);++ const storeInitialState = createMockState({+ settings: mockSettings({+ "token-features": createMockTokenFeatures({+ "transforms-testing": true,+ }),+ }),+ });+ setupEnterpriseOnlyPlugin("transforms-testing");++ const initialRoute = Urls.transformTestList(transform.id);+ const path = initialRoute.replace(`/${transform.id}/`, "/:transformId/");++ const { router } = renderWithProviders(+ <Route path={path} element={<TransformTestListPage />} />,+ { withRouter: true, initialRoute, storeInitialState },+ );+ return { router };+}++describe("TransformTestListPage", () => {+ it("lists the tests of the transform with their checks and last run", async () => {+ setup({+ tests: [+ createMockTransformTest({+ id: 1,+ name: "Refunded orders are excluded",+ expectations: [+ createMockTransformTestEqualsExpectation(),+ createMockTransformTestEmptyExpectation(),+ ],+ last_run: createMockTransformTestRun({ status: "passed" }),+ }),+ createMockTransformTest({+ id: 2,+ name: "Customers without paid orders are kept",+ last_run: createMockTransformTestRun({ id: 2, status: "failed" }),+ }),+ createMockTransformTest({ id: 3, name: "Country is always set" }),+ ],+ });++ const passedRow = await findRow("Refunded orders are excluded");+ expect(within(passedRow).getByText("2")).toBeInTheDocument();+ expect(within(passedRow).getByText(/Last run/)).toBeInTheDocument();++ const failedRow = await findRow("Customers without paid orders are kept");+ expect(within(failedRow).getByText(/Failed/)).toBeInTheDocument();++ const neverRunRow = await findRow("Country is always set");+ expect(+ within(neverRunRow).queryByText(/Last run|Failed/),+ ).not.toBeInTheDocument();+ });++ it("shows the Tests tab as selected", async () => {+ setup();++ expect(await screen.findByRole("link", { name: "Tests" })).toHaveAttribute(+ "aria-current",+ "page",+ );+ });++ it("shows an empty state when the transform has no tests", async () => {+ setup({ tests: [] });++ expect(await screen.findByText("No tests yet")).toBeInTheDocument();+ expect(+ screen.getAllByText(+ (_content, element) =>+ element?.textContent ===+ "Create tests with the mb CLI or with remote sync.",+ ),+ ).not.toHaveLength(0);+ expect(screen.getByText("mb", { selector: "code" })).toBeInTheDocument();+ });++ it("filters the tests by name", async () => {+ setup({+ tests: [+ createMockTransformTest({ id: 1, name: "Refunds" }),+ createMockTransformTest({ id: 2, name: "Countries" }),+ ],+ });++ await userEvent.type(+ await screen.findByPlaceholderText("Search..."),+ "count",+ );++ expect(screen.getByText("Countries")).toBeInTheDocument();+ expect(screen.queryByText("Refunds")).not.toBeInTheDocument();+ });++ it("runs a test from the row menu and reloads the list", async () => {+ setup({ tests: [createMockTransformTest({ id: 1, name: "Refunds" })] });+ setupRunTransformTestEndpoint(1, {+ status: "passed",+ expectations: [],+ tables: {},+ });++ const row = await findRow("Refunds");+ await userEvent.click(within(row).getByLabelText("Test options"));+ await userEvent.click(+ await screen.findByRole("menuitem", { name: /Run test/ }),+ );++ await waitFor(() => {+ expect(+ fetchMock.callHistory.called("path:/api/ee/transform-test/1/run", {+ method: "POST",+ }),+ ).toBe(true);+ });+ await waitFor(() => {+ expect(+ fetchMock.callHistory.calls("path:/api/ee/transform-test", {+ method: "GET",+ }),+ ).toHaveLength(2);+ });+ });++ it("opens a test when its row is clicked", async () => {+ const { router } = setup({+ tests: [+ createMockTransformTest({ id: 5, transform_id: 1, name: "Refunds" }),+ ],+ });++ await userEvent.click(await screen.findByText("Refunds"));++ expect(router?.location.pathname).toBe(Urls.transformTest(1, 5));+ });++ it("links to the runs of a test from the row menu", async () => {+ setup({+ tests: [+ createMockTransformTest({ id: 5, transform_id: 1, name: "Refunds" }),+ ],+ });++ const row = await findRow("Refunds");+ await userEvent.click(within(row).getByLabelText("Test options"));++ expect(+ await screen.findByRole("menuitem", { name: /View runs/ }),+ ).toHaveAttribute("href", Urls.transformTestRuns(1, 5));+ });++ it("hides the row menu from users who can't edit the transform", async () => {+ setup({+ tests: [createMockTransformTest({ id: 1, name: "Refunds" })],+ canWrite: false,+ });++ const row = await findRow("Refunds");+ expect(+ within(row).queryByLabelText("Test options"),+ ).not.toBeInTheDocument();+ });+});++function findRow(name: string) {+ return screen.findByRole("row", { name: new RegExp(name) });+}diff --git a/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestListPage/index.ts b/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestListPage/index.tsnew file mode 100644index 00000000000..39798cb09dd--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestListPage/index.ts@@ -0,0 +1 @@+export { TransformTestListPage } from "./TransformTestListPage";diff --git a/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestOverviewPage/TransformTestInputsSection/TransformTestInputsSection.tsx b/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestOverviewPage/TransformTestInputsSection/TransformTestInputsSection.tsxnew file mode 100644index 00000000000..b9297adc35e--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestOverviewPage/TransformTestInputsSection/TransformTestInputsSection.tsx@@ -0,0 +1,43 @@+import { msgid, ngettext, t } from "ttag";++import type { TransformTestInput } from "metabase-types/api";++import { TransformTestDataCard } from "../../../components/TransformTestDataCard";+import { TransformTestSection } from "../../../components/TransformTestSection";+import { getTableName } from "../../../utils";++type TransformTestInputsSectionProps = {+ inputs: TransformTestInput[];+};++export function TransformTestInputsSection({+ inputs,+}: TransformTestInputsSectionProps) {+ return (+ <TransformTestSection+ label={t`Inputs`}+ description={t`The transform reads this test data instead of the real tables.`}+ >+ {inputs.map((input) => {+ const name = getTableName(input.table);+ return (+ <TransformTestDataCard+ key={name}+ name={name}+ icon="table2"+ description={getInputDescription(input)}+ data={input}+ />+ );+ })}+ </TransformTestSection>+ );+}++function getInputDescription(input: TransformTestInput) {+ if (input.format === "sql") {+ return t`Rows returned by a query`;+ }+ const count = input.rows.length;+ return ngettext(msgid`${count} row`, `${count} rows`, count);+}diff --git a/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestOverviewPage/TransformTestInputsSection/index.ts b/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestOverviewPage/TransformTestInputsSection/index.tsnew file mode 100644index 00000000000..dad0839198e--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestOverviewPage/TransformTestInputsSection/index.ts@@ -0,0 +1 @@+export { TransformTestInputsSection } from "./TransformTestInputsSection";diff --git a/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestOverviewPage/TransformTestOutputSection/TransformTestOutputSection.tsx b/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestOverviewPage/TransformTestOutputSection/TransformTestOutputSection.tsxnew file mode 100644index 00000000000..9776aeb79ec--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestOverviewPage/TransformTestOutputSection/TransformTestOutputSection.tsx@@ -0,0 +1,58 @@+import { t } from "ttag";++import type {+ Transform,+ TransformTestData,+ TransformTestExpectation,+} from "metabase-types/api";++import { TransformTestDataCard } from "../../../components/TransformTestDataCard";+import { TransformTestSection } from "../../../components/TransformTestSection";+import { getTableName } from "../../../utils";++type TransformTestOutputSectionProps = {+ transform: Transform;+ expectations: TransformTestExpectation[];+};++export function TransformTestOutputSection({+ transform,+ expectations,+}: TransformTestOutputSectionProps) {+ const tableName = getTableName(transform.target);++ return (+ <TransformTestSection+ label={t`Output`}+ description={t`Checks on ${tableName}, the table this transform writes.`}+ >+ {expectations.map((expectation) => (+ <TransformTestDataCard+ key={expectation.name}+ name={expectation.name}+ icon="list"+ description={getExpectationDescription(expectation)}+ data={getExpectationData(expectation)}+ />+ ))}+ </TransformTestSection>+ );+}++function getExpectationDescription(expectation: TransformTestExpectation) {+ switch (expectation.type) {+ case "equals":+ return t`Must hold exactly these rows`;+ case "empty":+ return t`This query must return no rows`;+ }+}++function getExpectationData(+ expectation: TransformTestExpectation,+): TransformTestData {+ if (expectation.type === "empty") {+ return { format: "sql", sql: expectation.sql };+ }+ return expectation;+}diff --git a/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestOverviewPage/TransformTestOutputSection/index.ts b/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestOverviewPage/TransformTestOutputSection/index.tsnew file mode 100644index 00000000000..b3386257740--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestOverviewPage/TransformTestOutputSection/index.ts@@ -0,0 +1 @@+export { TransformTestOutputSection } from "./TransformTestOutputSection";diff --git a/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestOverviewPage/TransformTestOverviewPage.tsx b/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestOverviewPage/TransformTestOverviewPage.tsxnew file mode 100644index 00000000000..f381d369149--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestOverviewPage/TransformTestOverviewPage.tsx@@ -0,0 +1,35 @@+import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";+import { PageContainer } from "metabase/common/data-studio/components/PageContainer";+import { Center } from "metabase/ui";++import { TransformTestHeader } from "../../components/TransformTestHeader";+import { useRouteTransformTest } from "../../hooks/use-route-transform-test";++import { TransformTestInputsSection } from "./TransformTestInputsSection";+import { TransformTestOutputSection } from "./TransformTestOutputSection";+import { TransformTestRunSection } from "./TransformTestRunSection";++export function TransformTestOverviewPage() {+ const { transform, test, readOnly, isLoading, error } =+ useRouteTransformTest();++ if (transform == null || test == null || isLoading || error != null) {+ return (+ <Center h="100%">+ <LoadingAndErrorWrapper loading={isLoading} error={error} />+ </Center>+ );+ }++ return (+ <PageContainer data-testid="transform-test-overview">+ <TransformTestHeader transform={transform} test={test} />+ <TransformTestRunSection test={test} readOnly={readOnly} />+ <TransformTestInputsSection inputs={test.inputs} />+ <TransformTestOutputSection+ transform={transform}+ expectations={test.expectations}+ />+ </PageContainer>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestOverviewPage/TransformTestOverviewPage.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestOverviewPage/TransformTestOverviewPage.unit.spec.tsxnew file mode 100644index 00000000000..06c586fdf8f--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestOverviewPage/TransformTestOverviewPage.unit.spec.tsx@@ -0,0 +1,266 @@+import userEvent from "@testing-library/user-event";+import fetchMock from "fetch-mock";++import {+ setupCollectionByIdEndpoint,+ setupDatabasesEndpoints,+ setupGetTransformEndpoint,+ setupGetTransformTestEndpoint,+ setupRunTransformTestEndpoint,+} from "__support__/server-mocks";+import {+ mockGetBoundingClientRect,+ renderWithProviders,+ screen,+ waitFor,+ within,+} from "__support__/ui";+import { Route } from "metabase/router";+import * as Urls from "metabase/urls";+import type { TransformTest } from "metabase-types/api";+import {+ createMockCollection,+ createMockDatabase,+ createMockTransform,+ createMockTransformTest,+ createMockTransformTestEmptyExpectation,+ createMockTransformTestEqualsExpectation,+ createMockTransformTestRowsData,+ createMockTransformTestRun,+ createMockTransformTestSqlData,+} from "metabase-types/api/mocks";++import { TransformTestOverviewPage } from "./TransformTestOverviewPage";++type SetupOpts = {+ test?: TransformTest;+ canWrite?: boolean;+};++function setup({+ test = createMockTransformTest({+ id: 2,+ transform_id: 1,+ name: "Refunded orders are excluded",+ }),+ canWrite = true,+}: SetupOpts = {}) {+ mockGetBoundingClientRect({ width: 1000, height: 600 });+ const transform = createMockTransform({+ id: 1,+ name: "Customer revenue",+ target: {+ type: "table",+ schema: "analytics",+ name: "customer_revenue",+ database: 1,+ },+ });+ setupDatabasesEndpoints([+ createMockDatabase({+ id: 1,+ transforms_permissions: canWrite ? "write" : "none",+ }),+ ]);+ setupCollectionByIdEndpoint({+ collections: [createMockCollection({ id: "root" })],+ });+ setupGetTransformEndpoint(transform);+ setupGetTransformTestEndpoint(test);+ setupRunTransformTestEndpoint(test.id, {+ status: "passed",+ expectations: [],+ tables: {},+ });++ renderWithProviders(+ <Route+ path="/data-studio/transforms/:transformId/tests/:testId"+ element={<TransformTestOverviewPage />}+ />,+ {+ withRouter: true,+ initialRoute: Urls.transformTest(transform.id, test.id),+ },+ );+}++describe("TransformTestOverviewPage", () => {+ it("shows the test name with a breadcrumb back to the transform tests", async () => {+ setup();++ expect(+ await screen.findAllByText("Refunded orders are excluded"),+ ).toHaveLength(2);+ expect(+ await screen.findByRole("link", { name: "Customer revenue" }),+ ).toHaveAttribute("href", Urls.transformTestList(1));+ });++ it("says when the test has never run", async () => {+ setup();++ expect(+ await screen.findByText("This test hasn't been run before."),+ ).toBeInTheDocument();+ });++ it("shows a passed last run as successful", async () => {+ setup({+ test: createMockTransformTest({+ id: 2,+ transform_id: 1,+ last_run: createMockTransformTestRun({ status: "passed" }),+ }),+ });++ expect(+ await screen.findByText(/Last ran .* successfully/),+ ).toBeInTheDocument();+ });++ it("links to all runs of the test", async () => {+ setup({+ test: createMockTransformTest({+ id: 2,+ transform_id: 1,+ last_run: createMockTransformTestRun({ status: "passed" }),+ }),+ });++ expect(+ await screen.findByRole("link", { name: "See all runs" }),+ ).toHaveAttribute("href", Urls.transformTestRuns(1, 2));+ expect(screen.getByRole("link", { name: "Runs" })).toHaveAttribute(+ "href",+ Urls.transformTestRuns(1, 2),+ );+ });++ it("shows a failed last run as failed", async () => {+ setup({+ test: createMockTransformTest({+ id: 2,+ transform_id: 1,+ last_run: createMockTransformTestRun({ status: "failed" }),+ }),+ });++ expect(await screen.findByText(/Last run failed/)).toBeInTheDocument();+ });++ it("runs the test and reloads it", async () => {+ setup();++ await userEvent.click(+ await screen.findByRole("button", { name: /Run now/ }),+ );++ await waitFor(() => {+ expect(+ fetchMock.callHistory.called("path:/api/ee/transform-test/2/run", {+ method: "POST",+ }),+ ).toBe(true);+ });+ await waitFor(() => {+ expect(+ fetchMock.callHistory.calls("path:/api/ee/transform-test/2"),+ ).toHaveLength(2);+ });+ });++ it("disables running for users who can't edit the transform", async () => {+ setup({ canWrite: false });++ expect(+ await screen.findByRole("button", { name: /Run now/ }),+ ).toBeDisabled();+ });++ it("shows the rows and queries that stand in for the input tables", async () => {+ setup({+ test: createMockTransformTest({+ id: 2,+ transform_id: 1,+ inputs: [+ {+ table: { schema: "raw", name: "customers" },+ ...createMockTransformTestRowsData({+ columns: [+ { name: "id", cast_type: "int" },+ { name: "country", cast_type: "text" },+ ],+ rows: [+ { id: 1, country: "US" },+ { id: 2, country: null },+ ],+ }),+ },+ {+ table: { schema: "raw", name: "orders" },+ ...createMockTransformTestSqlData({+ sql: "SELECT 10 AS id, 'paid' AS status",+ }),+ },+ ],+ }),+ });++ const inputs = await screen.findByRole("region", { name: "Inputs" });+ const customers = within(inputs).getByLabelText("raw.customers");+ expect(within(customers).getByText("2 rows")).toBeInTheDocument();+ expect(within(customers).getByText("country")).toBeInTheDocument();+ expect(within(customers).getByText("US")).toBeInTheDocument();+ expect(within(customers).getByText("null")).toBeInTheDocument();++ const orders = within(inputs).getByLabelText("raw.orders");+ expect(+ within(orders).getByText("Rows returned by a query"),+ ).toBeInTheDocument();+ expect(+ await within(orders).findByText(/SELECT 10 AS id/),+ ).toBeInTheDocument();+ });++ it("shows the checks on the transform output", async () => {+ setup({+ test: createMockTransformTest({+ id: 2,+ transform_id: 1,+ expectations: [+ createMockTransformTestEqualsExpectation({+ name: "revenue per customer",+ columns: [{ name: "revenue", cast_type: "numeric" }],+ rows: [{ revenue: 120 }],+ }),+ createMockTransformTestEmptyExpectation({+ name: "no negative revenue",+ sql: "SELECT * FROM analytics.customer_revenue WHERE revenue < 0",+ }),+ ],+ }),+ });++ const output = await screen.findByRole("region", { name: "Output" });+ expect(+ within(output).getByText(+ "Checks on analytics.customer_revenue, the table this transform writes.",+ ),+ ).toBeInTheDocument();++ const equals = within(output).getByLabelText("revenue per customer");+ expect(+ within(equals).getByText("Must hold exactly these rows"),+ ).toBeInTheDocument();+ expect(within(equals).getByText("120")).toBeInTheDocument();++ const empty = within(output).getByLabelText("no negative revenue");+ expect(+ within(empty).getByText("This query must return no rows"),+ ).toBeInTheDocument();+ expect(+ await within(empty).findByText(/WHERE revenue < 0/),+ ).toBeInTheDocument();+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestOverviewPage/TransformTestRunSection/TransformTestRunSection.tsx b/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestOverviewPage/TransformTestRunSection/TransformTestRunSection.tsxnew file mode 100644index 00000000000..f43b13cfd18--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestOverviewPage/TransformTestRunSection/TransformTestRunSection.tsx@@ -0,0 +1,45 @@+import { t } from "ttag";++import { Link } from "metabase/common/components/Link";+import { TitleSection } from "metabase/common/data-studio/components/TitleSection";+import { RunStatus } from "metabase/transforms/components/RunStatus";+import { Anchor, Group } from "metabase/ui";+import * as Urls from "metabase/urls";+import type { TransformTest } from "metabase-types/api";++import { TransformTestRunButton } from "../../../components/TransformTestRunButton";+import { getRunStatusInfo } from "../../../utils";++type TransformTestRunSectionProps = {+ test: TransformTest;+ readOnly: boolean;+};++export function TransformTestRunSection({+ test,+ readOnly,+}: TransformTestRunSectionProps) {+ return (+ <TitleSection+ label={t`Run this test`}+ description={t`Runs the transform on the test data and checks its output. The real tables aren't touched.`}+ >+ <Group p="xl" justify="space-between">+ <RunStatus+ run={getRunStatusInfo(test.last_run)}+ neverRunMessage={t`This test hasn't been run before.`}+ runInfo={+ <Anchor+ component={Link}+ to={Urls.transformTestRuns(test.transform_id, test.id)}+ lh="inherit"+ >+ {t`See all runs`}+ </Anchor>+ }+ />+ <TransformTestRunButton test={test} readOnly={readOnly} />+ </Group>+ </TitleSection>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestOverviewPage/TransformTestRunSection/TransformTestRunSection.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestOverviewPage/TransformTestRunSection/TransformTestRunSection.unit.spec.tsxnew file mode 100644index 00000000000..46c06e7ee86--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestOverviewPage/TransformTestRunSection/TransformTestRunSection.unit.spec.tsx@@ -0,0 +1,34 @@+import { renderWithProviders, screen } from "__support__/ui";+import type { TransformTest } from "metabase-types/api";+import {+ createMockTransformTest,+ createMockTransformTestRun,+} from "metabase-types/api/mocks";++import { TransformTestRunSection } from "./TransformTestRunSection";++type SetupOpts = {+ test: TransformTest;+};++function setup({ test }: SetupOpts) {+ return renderWithProviders(+ <TransformTestRunSection test={test} readOnly={false} />,+ );+}++describe("TransformTestRunSection", () => {+ it("offers to run a test again when it re-renders with the same last run", () => {+ const test = createMockTransformTest({+ last_run: createMockTransformTestRun({ status: "passed" }),+ });+ const { rerender } = setup({ test });++ rerender(<TransformTestRunSection test={test} readOnly={false} />);++ expect(screen.getByRole("button", { name: /Run now/ })).toBeEnabled();+ expect(+ screen.queryByRole("button", { name: /Ran successfully/ }),+ ).not.toBeInTheDocument();+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestOverviewPage/TransformTestRunSection/index.ts b/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestOverviewPage/TransformTestRunSection/index.tsnew file mode 100644index 00000000000..217e9ddfd74--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestOverviewPage/TransformTestRunSection/index.ts@@ -0,0 +1 @@+export { TransformTestRunSection } from "./TransformTestRunSection";diff --git a/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestOverviewPage/index.ts b/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestOverviewPage/index.tsnew file mode 100644index 00000000000..de5d4738d78--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestOverviewPage/index.ts@@ -0,0 +1 @@+export { TransformTestOverviewPage } from "./TransformTestOverviewPage";diff --git a/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestRunsPage/TransformTestRunFilterBar/TransformTestRunFilterBar.tsx b/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestRunsPage/TransformTestRunFilterBar/TransformTestRunFilterBar.tsxnew file mode 100644index 00000000000..1d8ab81f7f0--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestRunsPage/TransformTestRunFilterBar/TransformTestRunFilterBar.tsx@@ -0,0 +1,73 @@+import { t } from "ttag";++import type { RelativeIntervalDirection } from "metabase/querying/common/types";+import { StatusFilterWidget } from "metabase/transforms/components/StatusFilterWidget";+import { TimeFilterWidget } from "metabase/transforms/components/TimeFilterWidget";+import { Group } from "metabase/ui";+import type * as Urls from "metabase/urls";+import {+ TRANSFORM_TEST_RUN_STATUSES,+ type TransformTestRunStatus,+} from "metabase-types/api";++import { formatTestRunStatus } from "../../../utils";++const PAST_INTERVAL_DIRECTIONS: RelativeIntervalDirection[] = [+ "past",+ "current",+];++type TransformTestRunFilterOptions = Omit<+ Urls.TransformTestRunListParams,+ "page"+>;++type TransformTestRunFilterBarProps = {+ filterOptions: TransformTestRunFilterOptions;+ onFilterOptionsChange: (filterOptions: TransformTestRunFilterOptions) => void;+};++export function TransformTestRunFilterBar({+ filterOptions,+ onFilterOptionsChange,+}: TransformTestRunFilterBarProps) {+ const statusOptions = TRANSFORM_TEST_RUN_STATUSES.map((status) => ({+ value: status,+ label: formatTestRunStatus(status),+ }));++ const handleStartTimeChange = (startTime: string | undefined) => {+ onFilterOptionsChange({ ...filterOptions, startTime });+ };++ const handleEndTimeChange = (endTime: string | undefined) => {+ onFilterOptionsChange({ ...filterOptions, endTime });+ };++ const handleStatusesChange = (statuses: TransformTestRunStatus[]) => {+ onFilterOptionsChange({ ...filterOptions, statuses });+ };++ return (+ <Group>+ <TimeFilterWidget+ label={t`Started at`}+ value={filterOptions.startTime}+ availableDirections={PAST_INTERVAL_DIRECTIONS}+ onChange={handleStartTimeChange}+ />+ <TimeFilterWidget+ label={t`Ended at`}+ value={filterOptions.endTime}+ availableDirections={PAST_INTERVAL_DIRECTIONS}+ onChange={handleEndTimeChange}+ />+ <StatusFilterWidget+ label={t`Status`}+ statuses={filterOptions.statuses ?? []}+ options={statusOptions}+ onChange={handleStatusesChange}+ />+ </Group>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestRunsPage/TransformTestRunFilterBar/index.ts b/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestRunsPage/TransformTestRunFilterBar/index.tsnew file mode 100644index 00000000000..823a436452b--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestRunsPage/TransformTestRunFilterBar/index.ts@@ -0,0 +1 @@+export { TransformTestRunFilterBar } from "./TransformTestRunFilterBar";diff --git a/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestRunsPage/TransformTestRunSidebar/TransformTestRunSidebar.module.css b/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestRunsPage/TransformTestRunSidebar/TransformTestRunSidebar.module.cssnew file mode 100644index 00000000000..77c6b127301--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestRunsPage/TransformTestRunSidebar/TransformTestRunSidebar.module.css@@ -0,0 +1,5 @@+.sidebar {+ flex: 1 1 auto;+ overflow: auto;+ border-left: 1px solid var(--mb-color-border-neutral);+}diff --git a/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestRunsPage/TransformTestRunSidebar/TransformTestRunSidebar.tsx b/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestRunsPage/TransformTestRunSidebar/TransformTestRunSidebar.tsxnew file mode 100644index 00000000000..3afea3e7fbd--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestRunsPage/TransformTestRunSidebar/TransformTestRunSidebar.tsx@@ -0,0 +1,105 @@+import { t } from "ttag";++import { DateTime } from "metabase/common/components/DateTime";+import { ForwardRefLink } from "metabase/common/components/Link";+import { SidebarResizableBox } from "metabase/common/components/SidebarResizableBox";+import { SidebarInfoRow } from "metabase/transforms/components/SidebarInfoRow";+import {+ ActionIcon,+ Anchor,+ Box,+ Card,+ FixedSizeIcon,+ Group,+ Stack,+ Title,+} from "metabase/ui";+import * as Urls from "metabase/urls";+import type {+ Transform,+ TransformTest,+ TransformTestRunWithUser,+} from "metabase-types/api";++import { formatTestRunStatus, isFailedTestRunStatus } from "../../../utils";++import S from "./TransformTestRunSidebar.module.css";++type TransformTestRunSidebarProps = {+ transform: Transform;+ test: TransformTest;+ run: TransformTestRunWithUser;+ containerWidth: number;+ onResizeStart: () => void;+ onResizeStop: () => void;+ onClose: () => void;+};++export function TransformTestRunSidebar({+ transform,+ test,+ run,+ containerWidth,+ onResizeStart,+ onResizeStop,+ onClose,+}: TransformTestRunSidebarProps) {+ return (+ <SidebarResizableBox+ containerWidth={containerWidth}+ onResizeStart={onResizeStart}+ onResizeStop={onResizeStop}+ >+ <Stack+ className={S.sidebar}+ p="xl"+ gap="xl"+ bg="background_page-primary"+ data-testid="transform-test-run-sidebar"+ >+ <Group gap="md" wrap="nowrap" align="start" justify="space-between">+ <Title order={3}>{test.name}</Title>+ <ActionIcon variant="subtle" aria-label={t`Close`} onClick={onClose}>+ <FixedSizeIcon name="close" />+ </ActionIcon>+ </Group>+ <Group gap="sm" wrap="nowrap">+ <FixedSizeIcon name="transform" c="core-brand" />+ <Anchor component={ForwardRefLink} to={Urls.transform(transform.id)}>+ {transform.name}+ </Anchor>+ </Group>+ <TransformTestRunInfo run={run} />+ </Stack>+ </SidebarResizableBox>+ );+}++function TransformTestRunInfo({ run }: { run: TransformTestRunWithUser }) {+ return (+ <Card p={0} shadow="none" withBorder role="region" aria-label={t`Info`}>+ <SidebarInfoRow label={t`Started at`}>+ <DateTime value={run.start_time} unit="minute" />+ </SidebarInfoRow>+ {run.end_time != null && (+ <SidebarInfoRow label={t`Ended at`}>+ <DateTime value={run.end_time} unit="minute" />+ </SidebarInfoRow>+ )}+ <SidebarInfoRow label={t`Status`}>+ <Box+ c={+ isFailedTestRunStatus(run.status) ? "feedback-negative" : undefined+ }+ >+ {formatTestRunStatus(run.status)}+ </Box>+ </SidebarInfoRow>+ {run.initiated_by_user != null && (+ <SidebarInfoRow label={t`Run by`}>+ {run.initiated_by_user.common_name}+ </SidebarInfoRow>+ )}+ </Card>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestRunsPage/TransformTestRunSidebar/index.ts b/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestRunsPage/TransformTestRunSidebar/index.tsnew file mode 100644index 00000000000..8606ea97b98--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestRunsPage/TransformTestRunSidebar/index.ts@@ -0,0 +1 @@+export { TransformTestRunSidebar } from "./TransformTestRunSidebar";diff --git a/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestRunsPage/TransformTestRunTable/TransformTestRunTable.tsx b/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestRunsPage/TransformTestRunTable/TransformTestRunTable.tsxnew file mode 100644index 00000000000..49f11d2153e--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestRunsPage/TransformTestRunTable/TransformTestRunTable.tsx@@ -0,0 +1,134 @@+import { t } from "ttag";++import { ListEmptyState } from "metabase/common/components/ListEmptyState";+import { useSetting } from "metabase/settings";+import { TimezoneIndicator } from "metabase/transforms/components/TimezoneIndicator";+import {+ getRunDurationMs,+ parseTimestampWithTimezone,+} from "metabase/transforms/utils";+import type { TreeTableColumnDef } from "metabase/ui";+import {+ Box,+ Card,+ Ellipsified,+ Group,+ SortableHeaderPill,+ TreeTable,+ useTreeTableInstance,+} from "metabase/ui";+import { EMPTY_CELL_PLACEHOLDER } from "metabase/utils/constants";+import { formatDurationLong } from "metabase/utils/formatting";+import type {+ TransformTestRunId,+ TransformTestRunWithUser,+} from "metabase-types/api";++import { formatTestRunStatus, isFailedTestRunStatus } from "../../../utils";++type TransformTestRunTableProps = {+ runs: TransformTestRunWithUser[];+ hasFilters: boolean;+ onSelect: (runId: TransformTestRunId) => void;+};++export function TransformTestRunTable({+ runs,+ hasFilters,+ onSelect,+}: TransformTestRunTableProps) {+ const systemTimezone = useSetting("system-timezone");++ const instance = useTreeTableInstance({+ data: runs,+ columns: getColumns(systemTimezone),+ getNodeId: (run) => String(run.id),+ });++ return (+ <Card withBorder p={0}>+ <TreeTable+ instance={instance}+ emptyState={+ <ListEmptyState+ label={hasFilters ? t`No runs found` : t`No runs yet`}+ />+ }+ ariaLabel={t`Test runs`}+ onRowClick={(row) => onSelect(row.original.id)}+ />+ </Card>+ );+}++function getColumns(+ systemTimezone: string | undefined,+): TreeTableColumnDef<TransformTestRunWithUser>[] {+ const formatTime = (time: string | null) =>+ time != null+ ? parseTimestampWithTimezone(time, systemTimezone).format("lll")+ : EMPTY_CELL_PLACEHOLDER;++ return [+ {+ id: "start-time",+ header: () => <TimeHeader name={t`Started at`} />,+ width: "auto",+ accessorFn: (run) => formatTime(run.start_time),+ cell: ({ getValue }) => <Ellipsified>{String(getValue())}</Ellipsified>,+ },+ {+ id: "end-time",+ header: () => <TimeHeader name={t`Ended at`} />,+ width: "auto",+ accessorFn: (run) => formatTime(run.end_time),+ cell: ({ getValue }) => <Ellipsified>{String(getValue())}</Ellipsified>,+ },+ {+ id: "duration",+ header: t`Duration`,+ width: 120,+ accessorFn: (run) => getRunDurationMs(run),+ cell: ({ getValue }) => {+ const durationMs = getValue<number | null>();+ return durationMs != null+ ? formatDurationLong(durationMs)+ : EMPTY_CELL_PLACEHOLDER;+ },+ },+ {+ id: "status",+ header: t`Status`,+ width: 120,+ accessorFn: (run) => formatTestRunStatus(run.status),+ cell: ({ row }) => (+ <Box+ c={+ isFailedTestRunStatus(row.original.status)+ ? "feedback-negative"+ : undefined+ }+ >+ {formatTestRunStatus(row.original.status)}+ </Box>+ ),+ },+ {+ id: "run-by",+ header: t`Run by`,+ width: "auto",+ accessorFn: (run) =>+ run.initiated_by_user?.common_name ?? EMPTY_CELL_PLACEHOLDER,+ cell: ({ getValue }) => <Ellipsified>{String(getValue())}</Ellipsified>,+ },+ ];+}++function TimeHeader({ name }: { name: string }) {+ return (+ <Group gap="xxs" wrap="nowrap">+ <SortableHeaderPill name={name} />+ <TimezoneIndicator />+ </Group>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestRunsPage/TransformTestRunTable/index.ts b/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestRunsPage/TransformTestRunTable/index.tsnew file mode 100644index 00000000000..c7721063e6b--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestRunsPage/TransformTestRunTable/index.ts@@ -0,0 +1 @@+export { TransformTestRunTable } from "./TransformTestRunTable";diff --git a/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestRunsPage/TransformTestRunsPage.module.css b/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestRunsPage/TransformTestRunsPage.module.cssnew file mode 100644index 00000000000..5780d690fe1--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestRunsPage/TransformTestRunsPage.module.css@@ -0,0 +1,7 @@+.main {+ overflow: hidden;+}++.resizing {+ user-select: none;+}diff --git a/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestRunsPage/TransformTestRunsPage.tsx b/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestRunsPage/TransformTestRunsPage.tsxnew file mode 100644index 00000000000..973d79c7548--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestRunsPage/TransformTestRunsPage.tsx@@ -0,0 +1,181 @@+import { useDisclosure, useElementSize } from "@mantine/hooks";+import cx from "classnames";+import { useState } from "react";++import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";+import { PaginationControls } from "metabase/common/components/PaginationControls";+import { PageContainer } from "metabase/common/data-studio/components/PageContainer";+import { useLocation, useNavigate } from "metabase/router";+import { POLLING_INTERVAL } from "metabase/transforms/constants";+import { Center, Flex, Group, Stack } from "metabase/ui";+import * as Urls from "metabase/urls";+import {+ useListTransformTestRunsQuery,+ useRunTransformTestMutation,+} from "metabase-enterprise/api";+import type {+ Transform,+ TransformTest,+ TransformTestRunId,+ TransformTestRunWithUser,+} from "metabase-types/api";++import { TransformTestHeader } from "../../components/TransformTestHeader";+import { TransformTestRunButton } from "../../components/TransformTestRunButton";+import { PAGE_SIZE } from "../../constants";+import { useRouteTransformTest } from "../../hooks/use-route-transform-test";+import { getRunTransformTestCacheKey } from "../../utils";++import { TransformTestRunFilterBar } from "./TransformTestRunFilterBar";+import { TransformTestRunSidebar } from "./TransformTestRunSidebar";+import { TransformTestRunTable } from "./TransformTestRunTable";+import S from "./TransformTestRunsPage.module.css";+import { getParsedParams } from "./utils";++const EMPTY_RUNS: TransformTestRunWithUser[] = [];++export function TransformTestRunsPage() {+ const { transform, test, readOnly, isLoading, error } =+ useRouteTransformTest();++ if (transform == null || test == null || isLoading || error != null) {+ return (+ <Center h="100%">+ <LoadingAndErrorWrapper loading={isLoading} error={error} />+ </Center>+ );+ }++ return (+ <TransformTestRuns transform={transform} test={test} readOnly={readOnly} />+ );+}++type TransformTestRunsProps = {+ transform: Transform;+ test: TransformTest;+ readOnly: boolean;+};++function TransformTestRuns({+ transform,+ test,+ readOnly,+}: TransformTestRunsProps) {+ const location = useLocation();+ const navigate = useNavigate();+ const params = getParsedParams(location);+ const { page = 0 } = params;+ const { ref: containerRef, width: containerWidth } = useElementSize();+ const [isResizing, { open: startResizing, close: stopResizing }] =+ useDisclosure();+ const [selectedRunId, setSelectedRunId] = useState<TransformTestRunId>();+ const [isPolling, setIsPolling] = useState(false);+ const [, { isLoading: isRunning }] = useRunTransformTestMutation({+ fixedCacheKey: getRunTransformTestCacheKey(test.id),+ });++ const { data, isLoading, error } = useListTransformTestRunsQuery(+ {+ id: test.id,+ offset: page * PAGE_SIZE,+ limit: PAGE_SIZE,+ statuses: params.statuses,+ "start-time": params.startTime,+ "end-time": params.endTime,+ },+ { pollingInterval: isPolling ? POLLING_INTERVAL : undefined },+ );+ const runs = data?.data ?? EMPTY_RUNS;+ const selectedRun = runs.find((run) => run.id === selectedRunId);+ const hasFilters =+ params.statuses != null ||+ params.startTime != null ||+ params.endTime != null;++ const shouldPoll = isRunning || runs.some((run) => run.status === "started");+ if (isPolling !== shouldPoll) {+ setIsPolling(shouldPoll);+ }++ const handleFilterOptionsChange = (+ filterOptions: Omit<Urls.TransformTestRunListParams, "page">,+ ) => {+ navigate(+ Urls.transformTestRuns(test.transform_id, test.id, filterOptions),+ { replace: true },+ );+ };++ const handlePageChange = (page: number) => {+ navigate(+ Urls.transformTestRuns(test.transform_id, test.id, { ...params, page }),+ { replace: true },+ );+ };++ return (+ <Flex+ className={cx({ [S.resizing]: isResizing })}+ ref={containerRef}+ h="100%"+ wrap="nowrap"+ >+ <PageContainer+ className={S.main}+ flex={1}+ data-testid="transform-test-runs"+ >+ <TransformTestHeader transform={transform} test={test} />+ <Stack gap="lg">+ <Group justify="space-between" align="center" wrap="nowrap">+ <TransformTestRunFilterBar+ filterOptions={{+ statuses: params.statuses,+ startTime: params.startTime,+ endTime: params.endTime,+ }}+ onFilterOptionsChange={handleFilterOptionsChange}+ />+ <TransformTestRunButton test={test} readOnly={readOnly} />+ </Group>+ {data == null || isLoading || error != null ? (+ <LoadingAndErrorWrapper loading={isLoading} error={error} />+ ) : (+ <>+ <TransformTestRunTable+ runs={runs}+ hasFilters={hasFilters}+ onSelect={setSelectedRunId}+ />+ {data.total > PAGE_SIZE && (+ <Group justify="end">+ <PaginationControls+ page={page}+ pageSize={PAGE_SIZE}+ itemsLength={runs.length}+ total={data.total}+ showTotal+ onPreviousPage={() => handlePageChange(page - 1)}+ onNextPage={() => handlePageChange(page + 1)}+ />+ </Group>+ )}+ </>+ )}+ </Stack>+ </PageContainer>+ {selectedRun != null && (+ <TransformTestRunSidebar+ transform={transform}+ test={test}+ run={selectedRun}+ containerWidth={containerWidth}+ onResizeStart={startResizing}+ onResizeStop={stopResizing}+ onClose={() => setSelectedRunId(undefined)}+ />+ )}+ </Flex>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestRunsPage/TransformTestRunsPage.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestRunsPage/TransformTestRunsPage.unit.spec.tsxnew file mode 100644index 00000000000..9ae16a7a159--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestRunsPage/TransformTestRunsPage.unit.spec.tsx@@ -0,0 +1,218 @@+import userEvent from "@testing-library/user-event";+import fetchMock from "fetch-mock";++import {+ setupCollectionByIdEndpoint,+ setupDatabasesEndpoints,+ setupGetTransformEndpoint,+ setupGetTransformTestEndpoint,+ setupListTransformTestRunsEndpoint,+ setupRunTransformTestEndpoint,+} from "__support__/server-mocks";+import {+ mockGetBoundingClientRect,+ renderWithProviders,+ screen,+ waitFor,+ within,+} from "__support__/ui";+import { Route } from "metabase/router";+import * as Urls from "metabase/urls";+import type { ListTransformTestRunsResponse } from "metabase-types/api";+import {+ createMockCollection,+ createMockDatabase,+ createMockListTransformTestRunsResponse,+ createMockTransform,+ createMockTransformTest,+ createMockTransformTestRunUser,+ createMockTransformTestRunWithUser,+} from "metabase-types/api/mocks";++import { TransformTestRunsPage } from "./TransformTestRunsPage";++type SetupOpts = {+ response?: ListTransformTestRunsResponse;+ initialRoute?: string;+};++function setup({+ response = createMockListTransformTestRunsResponse(),+ initialRoute = Urls.transformTestRuns(1, 2),+}: SetupOpts = {}) {+ mockGetBoundingClientRect({ width: 1000, height: 600 });+ setupDatabasesEndpoints([+ createMockDatabase({ id: 1, transforms_permissions: "write" }),+ ]);+ setupCollectionByIdEndpoint({+ collections: [createMockCollection({ id: "root" })],+ });+ setupGetTransformEndpoint(createMockTransform({ id: 1 }));+ setupGetTransformTestEndpoint(+ createMockTransformTest({ id: 2, transform_id: 1, name: "Refunds" }),+ );+ setupListTransformTestRunsEndpoint(2, response);+ setupRunTransformTestEndpoint(2, {+ status: "passed",+ expectations: [],+ tables: {},+ });++ const { router } = renderWithProviders(+ <Route+ path="/data-studio/transforms/:transformId/tests/:testId/runs"+ element={<TransformTestRunsPage />}+ />,+ { withRouter: true, initialRoute },+ );+ return { router };+}++function getLastRunsRequestUrl() {+ const call = fetchMock.callHistory.lastCall(+ "path:/api/ee/transform-test/2/run",+ { method: "GET" },+ );+ return new URL(call?.url ?? "", "http://localhost");+}++describe("TransformTestRunsPage", () => {+ it("lists the runs with their status and who started them", async () => {+ setup({+ response: createMockListTransformTestRunsResponse({+ data: [+ createMockTransformTestRunWithUser({+ id: 1,+ status: "failed",+ initiated_by_user: createMockTransformTestRunUser({+ common_name: "Ada Admin",+ }),+ }),+ createMockTransformTestRunWithUser({+ id: 2,+ status: "passed",+ initiated_by_user: null,+ }),+ ],+ total: 2,+ }),+ });++ const failedRow = await screen.findByRole("row", { name: /Ada Admin/ });+ expect(within(failedRow).getByText("Failed")).toBeInTheDocument();+ expect(within(failedRow).getByText("2.0s")).toBeInTheDocument();+ expect(screen.getByRole("row", { name: /Passed/ })).toBeInTheDocument();+ });++ it("shows an empty state when the test has no runs", async () => {+ setup();++ expect(await screen.findByText("No runs yet")).toBeInTheDocument();+ });++ it("requests the page from the URL and moves to the next page", async () => {+ const { router } = setup({+ response: createMockListTransformTestRunsResponse({+ data: [createMockTransformTestRunWithUser()],+ total: 60,+ offset: 25,+ }),+ initialRoute: Urls.transformTestRuns(1, 2, { page: 1 }),+ });++ await screen.findByText("26 - 26");+ expect(getLastRunsRequestUrl().searchParams.get("offset")).toBe("25");++ await userEvent.click(screen.getByLabelText("Next page"));++ expect(router?.location.search).toBe("?page=2");+ });++ it("runs the test", async () => {+ setup();++ await userEvent.click(+ await screen.findByRole("button", { name: /Run now/ }),+ );++ await waitFor(() => {+ expect(+ fetchMock.callHistory.called("path:/api/ee/transform-test/2/run", {+ method: "POST",+ }),+ ).toBe(true);+ });+ });++ it("requests the runs matching the filters in the URL", async () => {+ setup({+ initialRoute: Urls.transformTestRuns(1, 2, {+ statuses: ["failed", "error"],+ startTime: "past7days",+ }),+ });++ await screen.findByText("No runs found");+ const url = getLastRunsRequestUrl();+ expect(url.searchParams.getAll("statuses")).toEqual(["failed", "error"]);+ expect(url.searchParams.get("start-time")).toBe("past7days");+ });++ it("filters by status and goes back to the first page", async () => {+ const { router } = setup({+ initialRoute: Urls.transformTestRuns(1, 2, { page: 1 }),+ });++ await userEvent.click(await screen.findByLabelText("Status"));+ await userEvent.click(await screen.findByLabelText("Failed"));+ await userEvent.click(screen.getByRole("button", { name: "Add filter" }));++ expect(router?.location.search).toBe("?statuses=failed");+ });++ it("says no runs were found when filters are set", async () => {+ setup({+ initialRoute: Urls.transformTestRuns(1, 2, { statuses: ["failed"] }),+ });++ expect(await screen.findByText("No runs found")).toBeInTheDocument();+ });++ it("shows the details of a run in a sidebar", async () => {+ setup({+ response: createMockListTransformTestRunsResponse({+ data: [+ createMockTransformTestRunWithUser({+ id: 1,+ status: "failed",+ initiated_by_user: createMockTransformTestRunUser({+ common_name: "Ada Admin",+ }),+ }),+ ],+ total: 1,+ }),+ });++ await userEvent.click(+ await screen.findByRole("row", { name: /Ada Admin/ }),+ );++ const sidebar = await screen.findByTestId("transform-test-run-sidebar");+ const info = within(sidebar).getByRole("region", { name: "Info" });+ expect(+ within(info).getByRole("group", { name: "Status" }),+ ).toHaveTextContent("Failed");+ expect(+ within(info).getByRole("group", { name: "Run by" }),+ ).toHaveTextContent("Ada Admin");+ expect(+ within(info).getByRole("group", { name: "Started at" }),+ ).toBeInTheDocument();++ await userEvent.click(within(sidebar).getByLabelText("Close"));+ expect(+ screen.queryByTestId("transform-test-run-sidebar"),+ ).not.toBeInTheDocument();+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestRunsPage/index.ts b/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestRunsPage/index.tsnew file mode 100644index 00000000000..0acc2de0750--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestRunsPage/index.ts@@ -0,0 +1 @@+export { TransformTestRunsPage } from "./TransformTestRunsPage";diff --git a/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestRunsPage/utils.ts b/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestRunsPage/utils.tsnew file mode 100644index 00000000000..f8127f9bc1b--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/transforms-testing/pages/TransformTestRunsPage/utils.ts@@ -0,0 +1,18 @@+import type { Location } from "metabase/router";+import * as Urls from "metabase/urls";+import { TRANSFORM_TEST_RUN_STATUSES } from "metabase-types/api";++export function getParsedParams(+ location: Location,+): Urls.TransformTestRunListParams {+ const searchParams = new URLSearchParams(location.search);++ return {+ page: Urls.parseNumberParam(searchParams.get("page")),+ statuses: Urls.parseListParam(searchParams.getAll("statuses"), (value) =>+ Urls.parseEnumParam(value, TRANSFORM_TEST_RUN_STATUSES),+ ),+ startTime: Urls.parseStringParam(searchParams.get("start-time")),+ endTime: Urls.parseStringParam(searchParams.get("end-time")),+ };+}diff --git a/enterprise/frontend/src/metabase-enterprise/transforms-testing/routes.tsx b/enterprise/frontend/src/metabase-enterprise/transforms-testing/routes.tsxnew file mode 100644index 00000000000..50f74a4c384--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/transforms-testing/routes.tsx@@ -0,0 +1,32 @@+import { Route } from "metabase/router";++const testListPage = () =>+ import(+ /* webpackChunkName: "transforms-testing" */ "./pages/TransformTestListPage"+ ).then(({ TransformTestListPage }) => ({+ Component: TransformTestListPage,+ }));++const testOverviewPage = () =>+ import(+ /* webpackChunkName: "transforms-testing" */ "./pages/TransformTestOverviewPage"+ ).then(({ TransformTestOverviewPage }) => ({+ Component: TransformTestOverviewPage,+ }));++const testRunsPage = () =>+ import(+ /* webpackChunkName: "transforms-testing" */ "./pages/TransformTestRunsPage"+ ).then(({ TransformTestRunsPage }) => ({+ Component: TransformTestRunsPage,+ }));++export function getTransformTestRoutes() {+ return (+ <>+ <Route path=":transformId/tests" lazy={testListPage} />+ <Route path=":transformId/tests/:testId" lazy={testOverviewPage} />+ <Route path=":transformId/tests/:testId/runs" lazy={testRunsPage} />+ </>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/transforms-testing/utils.ts b/enterprise/frontend/src/metabase-enterprise/transforms-testing/utils.tsnew file mode 100644index 00000000000..5858ded7afa--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/transforms-testing/utils.ts@@ -0,0 +1,67 @@+import { t } from "ttag";++import type {+ TransformRun,+ TransformRunStatus,+ TransformTestId,+ TransformTestRun,+ TransformTestRunStatus,+ TransformTestTable,+} from "metabase-types/api";++const TRANSFORM_RUN_STATUSES: Record<+ TransformTestRunStatus,+ TransformRunStatus+> = {+ started: "started",+ passed: "succeeded",+ failed: "failed",+ error: "failed",+ timeout: "timeout",+};++export function getTransformRunStatus(+ status: TransformTestRunStatus,+): TransformRunStatus {+ return TRANSFORM_RUN_STATUSES[status];+}++export function getRunStatusInfo(+ run: TransformTestRun | null,+): Pick<TransformRun, "status" | "end_time" | "message"> | null {+ if (run == null) {+ return null;+ }+ return {+ status: getTransformRunStatus(run.status),+ end_time: run.end_time,+ message: null,+ };+}++export function getTableName(table: TransformTestTable) {+ return table.schema ? `${table.schema}.${table.name}` : table.name;+}++export function formatTestRunStatus(status: TransformTestRunStatus) {+ switch (status) {+ case "started":+ return t`In progress`;+ case "passed":+ return t`Passed`;+ case "failed":+ return t`Failed`;+ case "error":+ return t`Error`;+ case "timeout":+ return t`Timeout`;+ }+}++export function isFailedTestRunStatus(status: TransformTestRunStatus) {+ return status === "failed" || status === "error" || status === "timeout";+}++export function getRunTransformTestCacheKey(testId: TransformTestId) {+ return `run-transform-test-${testId}`;+}diff --git a/frontend/lint/module-boundaries.mjs b/frontend/lint/module-boundaries.mjsindex 09c6e00ed07..0c3a72c0726 100644--- a/frontend/lint/module-boundaries.mjs+++ b/frontend/lint/module-boundaries.mjs@@ -339,13 +339,13 @@ const elements = [createElement({type: "feature",name: "data-app-sandbox",- pattern: "enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/**",+ pattern: "enterprise/frontend/src/metabase-enterprise/data-apps/sandbox/**",mode: "full",}),createElement({type: "app",name: "data-app-runtime",- pattern: "enterprise/frontend/src/metabase-enterprise/data_apps/runtime/**",+ pattern: "enterprise/frontend/src/metabase-enterprise/data-apps/runtime/**",mode: "full",}),createElement({diff --git a/frontend/lint/side-effect-files.json b/frontend/lint/side-effect-files.jsonindex c0227544806..ba9b9aed834 100644--- a/frontend/lint/side-effect-files.json+++ b/frontend/lint/side-effect-files.json@@ -49,8 +49,8 @@"enterprise/frontend/src/metabase-enterprise/auth/constants.ts": "self","enterprise/frontend/src/metabase-enterprise/auth/index.ts": "global","enterprise/frontend/src/metabase-enterprise/custom_viz/components/CustomVizPage.tsx": "self",- "enterprise/frontend/src/metabase-enterprise/data_apps/runtime/app-data-app.tsx": "entry",- "enterprise/frontend/src/metabase-enterprise/data_apps/runtime/iframe-vendors.ts": "entry",+ "enterprise/frontend/src/metabase-enterprise/data-apps/runtime/app-data-app.tsx": "entry",+ "enterprise/frontend/src/metabase-enterprise/data-apps/runtime/iframe-vendors.ts": "entry","enterprise/frontend/src/metabase-enterprise/database_replication/DatabaseReplicationForm.tsx": "self","enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/DependencyGraph.tsx": "self","enterprise/frontend/src/metabase-enterprise/embedding/index.ts": "global",diff --git a/frontend/src/metabase-types/api/index.ts b/frontend/src/metabase-types/api/index.tsindex b6c67608f9b..0103fa7c6a3 100644--- a/frontend/src/metabase-types/api/index.ts+++ b/frontend/src/metabase-types/api/index.ts@@ -78,6 +78,7 @@ export * from "./task";export * from "./tenants";export * from "./timeline";export * from "./transform";+export * from "./transform-test";export * from "./user";export * from "./util";export * from "./visualization";diff --git a/frontend/src/metabase-types/api/mocks/data-app.ts b/frontend/src/metabase-types/api/mocks/data-app.tsindex c3b80b45729..6c61554be0b 100644--- a/frontend/src/metabase-types/api/mocks/data-app.ts+++ b/frontend/src/metabase-types/api/mocks/data-app.ts@@ -1,4 +1,9 @@-import type { DataApp } from "metabase-types/api";+import type {+ DataApp,+ DataAppGroup,+ DataAppGroupPermissionWarning,+ DataAppMissingTable,+} from "metabase-types/api";export const createMockDataApp = (opts?: Partial<DataApp>): DataApp => ({id: 1,@@ -17,3 +22,31 @@ export const createMockDataApp = (opts?: Partial<DataApp>): DataApp => ({updated_at: "2024-01-01T00:00:00Z",...opts,});++export const createMockDataAppGroup = (+ opts?: Partial<DataAppGroup>,+): DataAppGroup => ({+ id: 1,+ name: "Support",+ member_count: 0,+ ...opts,+});++export const createMockDataAppMissingTable = (+ opts?: Partial<DataAppMissingTable>,+): DataAppMissingTable => ({+ id: 1,+ name: "Orders",+ schema: "public",+ database_id: 1,+ database_name: "Shop",+ ...opts,+});++export const createMockDataAppGroupPermissionWarning = (+ opts?: Partial<DataAppGroupPermissionWarning>,+): DataAppGroupPermissionWarning => ({+ group_id: 1,+ missing_tables: [createMockDataAppMissingTable()],+ ...opts,+});diff --git a/frontend/src/metabase-types/api/mocks/index.ts b/frontend/src/metabase-types/api/mocks/index.tsindex 6f9289cbe1c..535cbc10072 100644--- a/frontend/src/metabase-types/api/mocks/index.ts+++ b/frontend/src/metabase-types/api/mocks/index.ts@@ -53,5 +53,6 @@ export * from "./task";export * from "./tenant";export * from "./timeline";export * from "./transform";+export * from "./transform-test";export * from "./user";export * from "./util";diff --git a/frontend/src/metabase-types/api/mocks/transform-test.ts b/frontend/src/metabase-types/api/mocks/transform-test.tsnew file mode 100644index 00000000000..c1512eada5d--- /dev/null+++ b/frontend/src/metabase-types/api/mocks/transform-test.ts@@ -0,0 +1,133 @@+import type {+ ListTransformTestRunsResponse,+ TransformTest,+ TransformTestEmptyExpectation,+ TransformTestEqualsExpectation,+ TransformTestRowsData,+ TransformTestRun,+ TransformTestRunUser,+ TransformTestRunWithUser,+ TransformTestSqlData,+} from "metabase-types/api";++export function createMockTransformTestRowsData(+ opts?: Partial<TransformTestRowsData>,+): TransformTestRowsData {+ return {+ format: "rows",+ columns: [{ name: "id", cast_type: "int" }],+ rows: [{ id: 1 }],+ ...opts,+ };+}++export function createMockTransformTestSqlData(+ opts?: Partial<TransformTestSqlData>,+): TransformTestSqlData {+ return {+ format: "sql",+ sql: "SELECT 1 AS id",+ ...opts,+ };+}++type TransformTestEqualsRowsExpectation = Extract<+ TransformTestEqualsExpectation,+ { format: "rows" }+>;++export function createMockTransformTestEqualsExpectation(+ opts?: Partial<TransformTestEqualsRowsExpectation>,+): TransformTestEqualsRowsExpectation {+ return {+ type: "equals",+ name: "output rows",+ ...createMockTransformTestRowsData(),+ ...opts,+ };+}++export function createMockTransformTestEmptyExpectation(+ opts?: Partial<TransformTestEmptyExpectation>,+): TransformTestEmptyExpectation {+ return {+ type: "empty",+ name: "no rows",+ sql: "SELECT * FROM output WHERE id IS NULL",+ ...opts,+ };+}++export function createMockTransformTestRun(+ opts?: Partial<TransformTestRun>,+): TransformTestRun {+ return {+ id: 1,+ transform_test_id: 1,+ initiated_by: 1,+ start_time: "2026-01-01T00:00:00Z",+ end_time: "2026-01-01T00:00:02Z",+ status: "passed",+ last_heartbeat: "2026-01-01T00:00:02Z",+ ...opts,+ };+}++export function createMockTransformTestRunUser(+ opts?: Partial<TransformTestRunUser>,+): TransformTestRunUser {+ return {+ id: 1,+ email: "[email protected]",+ first_name: "Test",+ last_name: "User",+ common_name: "Test User",+ ...opts,+ };+}++export function createMockTransformTestRunWithUser(+ opts?: Partial<TransformTestRunWithUser>,+): TransformTestRunWithUser {+ return {+ ...createMockTransformTestRun(),+ initiated_by_user: createMockTransformTestRunUser(),+ ...opts,+ };+}++export function createMockListTransformTestRunsResponse(+ opts?: Partial<ListTransformTestRunsResponse>,+): ListTransformTestRunsResponse {+ return {+ data: [],+ limit: 20,+ offset: 0,+ total: 0,+ ...opts,+ };+}++export function createMockTransformTest(+ opts?: Partial<TransformTest>,+): TransformTest {+ return {+ id: 1,+ entity_id: "transform-test-1",+ transform_id: 1,+ creator_id: 1,+ name: "Test",+ description: null,+ inputs: [+ {+ table: { schema: "public", name: "orders" },+ ...createMockTransformTestRowsData(),+ },+ ],+ expectations: [createMockTransformTestEqualsExpectation()],+ created_at: "2026-01-01T00:00:00Z",+ updated_at: "2026-01-01T00:00:00Z",+ last_run: null,+ ...opts,+ };+}diff --git a/frontend/src/metabase-types/api/transform-test.ts b/frontend/src/metabase-types/api/transform-test.tsnew file mode 100644index 00000000000..d37fcd09a3a--- /dev/null+++ b/frontend/src/metabase-types/api/transform-test.ts@@ -0,0 +1,124 @@+import type { PaginationRequest, PaginationResponse } from "./pagination";+import type { TransformId } from "./transform";+import type { UserId, UserInfo } from "./user";++export type TransformTestId = number;+export type TransformTestRunId = number;++export type TransformTestTable = {+ schema?: string | null;+ name: string;+};++export type TransformTestColumn = {+ name: string;+ cast_type: string;+};++export type TransformTestRowValue = string | number | boolean | null;+export type TransformTestRow = Record<string, TransformTestRowValue>;++export type TransformTestRowsData = {+ format: "rows";+ columns: TransformTestColumn[];+ rows: TransformTestRow[];+};++export type TransformTestSqlData = {+ format: "sql";+ sql: string;+};++export type TransformTestData = TransformTestRowsData | TransformTestSqlData;++export type TransformTestInput = {+ table: TransformTestTable;+} & TransformTestData;++export type TransformTestEqualsExpectation = {+ type: "equals";+ name: string;+} & TransformTestData;++export type TransformTestEmptyExpectation = {+ type: "empty";+ name: string;+ sql: string;+};++export type TransformTestExpectation =+ | TransformTestEqualsExpectation+ | TransformTestEmptyExpectation;++export const TRANSFORM_TEST_RUN_STATUSES = [+ "started",+ "passed",+ "failed",+ "error",+ "timeout",+] as const;+export type TransformTestRunStatus =+ (typeof TRANSFORM_TEST_RUN_STATUSES)[number];++export type TransformTestRun = {+ id: TransformTestRunId;+ transform_test_id: TransformTestId | null;+ initiated_by: UserId | null;+ start_time: string;+ end_time: string | null;+ status: TransformTestRunStatus;+ last_heartbeat: string;+};++export type TransformTestRunUser = Pick<+ UserInfo,+ "id" | "email" | "first_name" | "last_name" | "common_name"+>;++export type TransformTestRunWithUser = TransformTestRun & {+ initiated_by_user: TransformTestRunUser | null;+};++export type TransformTest = {+ id: TransformTestId;+ entity_id: string;+ transform_id: TransformId;+ creator_id: UserId;+ name: string;+ description: string | null;+ inputs: TransformTestInput[];+ expectations: TransformTestExpectation[];+ created_at: string;+ updated_at: string;+ last_run: TransformTestRun | null;+};++export type ListTransformTestsRequest = {+ "transform-id"?: TransformId;+};++export type ListTransformTestRunsRequest = {+ id: TransformTestId;+ statuses?: TransformTestRunStatus[];+ "start-time"?: string;+ "end-time"?: string;+} & PaginationRequest;++export type ListTransformTestRunsResponse = {+ data: TransformTestRunWithUser[];+} & PaginationResponse;++export type TransformTestResultStatus = "passed" | "failed" | "error";++export type TransformTestExpectationResult = {+ name: string;+ type: TransformTestExpectation["type"];+ status: TransformTestResultStatus;+ error?: { type: string; message: string };+};++export type RunTransformTestResponse = {+ status: TransformTestResultStatus;+ expectations: TransformTestExpectationResult[];+ tables: Record<string, string>;+};diff --git a/frontend/src/metabase-types/guards/readme.md b/frontend/src/metabase-types/guards/readme.mdindex 9cf3248d89b..993268bbd00 100644--- a/frontend/src/metabase-types/guards/readme.md+++ b/frontend/src/metabase-types/guards/readme.md@@ -2,7 +2,7 @@Place all reusable type guard functions in this directory. To help keep things organized, please name the guards files in parallel to their corresponding type definition files from the `/api` directory.-Type guards are functions that take a value and return a boolean indicating whether or not the value is of a certain type. For example:+Type guards are functions that take a value and return a boolean indicating whether or not the value is of a certain type. For example:```tsfunction isString(value) {@@ -24,5 +24,4 @@ if (isFish(pet)) {}```-https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicatesdiff --git a/frontend/src/metabase/admin/settings/components/SettingsNav/DataAppsNav.tsx b/frontend/src/metabase/admin/settings/components/SettingsNav/DataAppsNav.tsxdeleted file mode 100644index e5db9277483..00000000000--- a/frontend/src/metabase/admin/settings/components/SettingsNav/DataAppsNav.tsx+++ /dev/null@@ -1,25 +0,0 @@-import { t } from "ttag";--import { UpsellGem } from "metabase/common/components/upsells/components";-import { useHasTokenFeature } from "metabase/common/hooks";-import { Flex } from "metabase/ui";-import * as Urls from "metabase/urls";--import { SettingsNavItem } from "./SettingsNavItem";--export const DataAppsNav = () => {- const hasDataApps = useHasTokenFeature("data-apps");-- return (- <SettingsNavItem- path={Urls.DATA_APP_URL_SEGMENT}- icon="app"- label={- <Flex gap="sm" align="center">- <span>{t`Data apps`}</span>- {!hasDataApps && <UpsellGem />}- </Flex>- }- />- );-};diff --git a/frontend/src/metabase/admin/settings/components/SettingsNav/SettingsNav.tsx b/frontend/src/metabase/admin/settings/components/SettingsNav/SettingsNav.tsxindex e79e4a42059..68e3f79bb25 100644--- a/frontend/src/metabase/admin/settings/components/SettingsNav/SettingsNav.tsx+++ b/frontend/src/metabase/admin/settings/components/SettingsNav/SettingsNav.tsx@@ -8,7 +8,6 @@ import { getPlan, isProPlan, useSetting } from "metabase/settings";import { Box, Divider, Flex } from "metabase/ui";import { CustomVisualizationsNav } from "./CustomVisualizationsNav";-import { DataAppsNav } from "./DataAppsNav";import { SettingsNavItem } from "./SettingsNavItem";import { UpdatesNavItem } from "./UpdatesNavItem";@@ -77,7 +76,6 @@ export function SettingsNav() {icon="pinmap"/><CustomVisualizationsNav />- <DataAppsNav /><SettingsNavItem path="maps" label={t`Maps`} icon="map" /><SettingsNavItempath={!hasWhitelabel ? "whitelabel" : undefined}diff --git a/frontend/src/metabase/admin/settings/components/SettingsPages/DataAppsSettingsPage.tsx b/frontend/src/metabase/admin/settings/components/SettingsPages/DataAppsSettingsPage.tsxdeleted file mode 100644index 8e8f6ef3037..00000000000--- a/frontend/src/metabase/admin/settings/components/SettingsPages/DataAppsSettingsPage.tsx+++ /dev/null@@ -1,28 +0,0 @@-import { t } from "ttag";--import { UpsellDataApps } from "metabase/admin/upsells";-import { useHasTokenFeature } from "metabase/common/hooks";-import { PLUGIN_DATA_APPS } from "metabase/plugins";-import { SettingsPageWrapper } from "metabase/settings-components";--/**- * Admin page at /admin/settings/apps. Shows the upsell on instances without the- * `data-apps` token feature; the enterprise plugin provides the management UI.- */-export function DataAppsManagePage() {- const hasDataApps = useHasTokenFeature("data-apps");-- if (!hasDataApps) {- return (- <SettingsPageWrapper title={t`Data apps`}>- <UpsellDataApps source="settings-data-apps" />- </SettingsPageWrapper>- );- }-- return <PLUGIN_DATA_APPS.ManageDataAppsPage />;-}--export function DataAppGroupsManagePage() {- return <PLUGIN_DATA_APPS.ManageDataAppGroupsPage />;-}diff --git a/frontend/src/metabase/admin/settingsRoutes.tsx b/frontend/src/metabase/admin/settingsRoutes.tsxindex 587ff66b85c..36d90e91384 100644--- a/frontend/src/metabase/admin/settingsRoutes.tsx+++ b/frontend/src/metabase/admin/settingsRoutes.tsx@@ -135,18 +135,6 @@ const customVisualizationsDevelopment = () =>Component: CustomVisualizationsDevelopmentPage,}));-const dataAppsManage = () =>- import(- /* webpackChunkName: "admin-settings" */ "./settings/components/SettingsPages/DataAppsSettingsPage"- ).then(({ DataAppsManagePage }) => ({ Component: DataAppsManagePage }));--const dataAppGroupsManage = () =>- import(- /* webpackChunkName: "admin-settings" */ "./settings/components/SettingsPages/DataAppsSettingsPage"- ).then(({ DataAppGroupsManagePage }) => ({- Component: DataAppGroupsManagePage,- }));-const uploadSettings = () =>import(/* webpackChunkName: "admin-settings" */ "./settings/components/SettingsPages/UploadSettingsPage"@@ -242,10 +230,6 @@ export const getSettingsRoutes = (store: Store<State>) => {<Route path="development" lazy={customVisualizationsDevelopment} />)}</Route>- <Route path={Urls.DATA_APP_URL_SEGMENT}>- <Route index lazy={dataAppsManage} />- <Route path=":slug/groups" lazy={dataAppGroupsManage} />- </Route><Route path="uploads" lazy={uploadSettings} /><Routepath="python-runner"diff --git a/frontend/src/metabase/admin/upsells/UpsellDataApps.tsx b/frontend/src/metabase/admin/upsells/UpsellDataApps.tsxdeleted file mode 100644index c4241175d54..00000000000--- a/frontend/src/metabase/admin/upsells/UpsellDataApps.tsx+++ /dev/null@@ -1,36 +0,0 @@-import { t } from "ttag";--import upsellDataAppsImage from "assets/img/upsell-data-apps.png?url";-import { UpsellBigCard } from "metabase/common/components/upsells/components";-import { UPGRADE_URL } from "metabase/common/components/upsells/constants";-import { useHasTokenFeature } from "metabase/common/hooks";-import { PLUGIN_ADMIN_SETTINGS } from "metabase/plugins";--export const UpsellDataApps = ({ source }: { source: string }) => {- const hasDataApps = useHasTokenFeature("data-apps");- const campaign = "data-apps";- const { triggerUpsellFlow } = PLUGIN_ADMIN_SETTINGS.useUpsellFlow({- campaign,- location: source,- });-- if (hasDataApps) {- return null;- }-- return (- <UpsellBigCard- title={t`Build custom data apps`}- campaign={campaign}- buttonText={t`Try for free`}- buttonLink={UPGRADE_URL}- source={source}- illustrationSrc={upsellDataAppsImage}- onClick={triggerUpsellFlow}- >- <span>- {t`Build custom user interfaces, forms, and other tools that write back to your database. Automate chores, manage back-office work, and set up workflows to act on your data, all built with AI on top of your semantic layer.`}- </span>- </UpsellBigCard>- );-};diff --git a/frontend/src/metabase/admin/upsells/index.ts b/frontend/src/metabase/admin/upsells/index.tsindex 2afca3acef0..596bd486f19 100644--- a/frontend/src/metabase/admin/upsells/index.ts+++ b/frontend/src/metabase/admin/upsells/index.ts@@ -2,7 +2,6 @@ export * from "./UpsellBetterSupport";export * from "./UpsellCacheConfig";export * from "./UpsellCloud";export * from "./UpsellCustomViz";-export * from "./UpsellDataApps";export * from "./UpsellEmailWhitelabel";export * from "./UpsellHosting";export * from "./UpsellPermissions";diff --git a/frontend/src/metabase/common/components/ListEmptyState/ListEmptyState.tsx b/frontend/src/metabase/common/components/ListEmptyState/ListEmptyState.tsxindex abca4de4a14..a25a39cff3e 100644--- a/frontend/src/metabase/common/components/ListEmptyState/ListEmptyState.tsx+++ b/frontend/src/metabase/common/components/ListEmptyState/ListEmptyState.tsx@@ -7,7 +7,7 @@ import { Box, Stack, Text } from "metabase/ui";type ListEmptyStateProps = {label: string;- description?: string;+ description?: ReactNode;action?: ReactNode;};diff --git a/enterprise/frontend/src/metabase-enterprise/replacement/pages/MigrateModelsPage/ModelSidebar/SidebarResizableBox/SidebarResizableBox.module.css b/frontend/src/metabase/common/components/SidebarResizableBox/SidebarResizableBox.module.csssimilarity index 100%rename from enterprise/frontend/src/metabase-enterprise/replacement/pages/MigrateModelsPage/ModelSidebar/SidebarResizableBox/SidebarResizableBox.module.cssrename to frontend/src/metabase/common/components/SidebarResizableBox/SidebarResizableBox.module.cssdiff --git a/enterprise/frontend/src/metabase-enterprise/replacement/pages/MigrateModelsPage/ModelSidebar/SidebarResizableBox/SidebarResizableBox.tsx b/frontend/src/metabase/common/components/SidebarResizableBox/SidebarResizableBox.tsxsimilarity index 100%rename from enterprise/frontend/src/metabase-enterprise/replacement/pages/MigrateModelsPage/ModelSidebar/SidebarResizableBox/SidebarResizableBox.tsxrename to frontend/src/metabase/common/components/SidebarResizableBox/SidebarResizableBox.tsxdiff --git a/frontend/src/metabase/transforms/components/SidebarResizableBox/index.ts b/frontend/src/metabase/common/components/SidebarResizableBox/index.tssimilarity index 100%rename from frontend/src/metabase/transforms/components/SidebarResizableBox/index.tsrename to frontend/src/metabase/common/components/SidebarResizableBox/index.tsdiff --git a/frontend/src/metabase/common/data-studio/components/AboutSidebar/AboutHeader/AboutHeader.tsx b/frontend/src/metabase/common/data-studio/components/AboutSidebar/AboutHeader/AboutHeader.tsxnew file mode 100644index 00000000000..90866537162--- /dev/null+++ b/frontend/src/metabase/common/data-studio/components/AboutSidebar/AboutHeader/AboutHeader.tsx@@ -0,0 +1,28 @@+import { t } from "ttag";++import { DateTime } from "metabase/common/components/DateTime";+import { Text, Tooltip } from "metabase/ui";+import { getRelativeTime } from "metabase/utils/time-dayjs";++interface AboutHeaderProps {+ updatedAt: string;+}++export function AboutHeader({ updatedAt }: AboutHeaderProps) {+ return (+ <>+ <Text fz="lg" fw={700}>{t`About`}</Text>+ <Tooltip label={<DateTime value={updatedAt} />} offset={8}>+ <Text+ size="sm"+ c="text-secondary"+ w="fit-content"+ mt="sm"+ data-testid="about-last-updated"+ >+ {t`Last updated ${getRelativeTime(updatedAt)}`}+ </Text>+ </Tooltip>+ </>+ );+}diff --git a/frontend/src/metabase/common/data-studio/components/AboutSidebar/AboutHeader/index.ts b/frontend/src/metabase/common/data-studio/components/AboutSidebar/AboutHeader/index.tsnew file mode 100644index 00000000000..fd8345f3a80--- /dev/null+++ b/frontend/src/metabase/common/data-studio/components/AboutSidebar/AboutHeader/index.ts@@ -0,0 +1 @@+export { AboutHeader } from "./AboutHeader";diff --git a/frontend/src/metabase/common/data-studio/components/AboutSidebar/AboutSidebar.tsx b/frontend/src/metabase/common/data-studio/components/AboutSidebar/AboutSidebar.tsxnew file mode 100644index 00000000000..532d2da688e--- /dev/null+++ b/frontend/src/metabase/common/data-studio/components/AboutSidebar/AboutSidebar.tsx@@ -0,0 +1,15 @@+import type { ReactNode } from "react";++import { Stack, type StackProps } from "metabase/ui";++interface AboutSidebarProps extends StackProps {+ children: ReactNode;+}++export function AboutSidebar({ children, ...stackProps }: AboutSidebarProps) {+ return (+ <Stack p="lg" gap={0} align="stretch" {...stackProps}>+ {children}+ </Stack>+ );+}diff --git a/frontend/src/metabase/metrics/pages/MetricAboutPage/MetricAbout/DescriptionSection/MetricSubSection.tsx b/frontend/src/metabase/common/data-studio/components/AboutSidebar/AboutSubSection/AboutSubSection.tsxsimilarity index 73%rename from frontend/src/metabase/metrics/pages/MetricAboutPage/MetricAbout/DescriptionSection/MetricSubSection.tsxrename to frontend/src/metabase/common/data-studio/components/AboutSidebar/AboutSubSection/AboutSubSection.tsxindex b49480972d6..fc80580534f 100644--- a/frontend/src/metabase/metrics/pages/MetricAboutPage/MetricAbout/DescriptionSection/MetricSubSection.tsx+++ b/frontend/src/metabase/common/data-studio/components/AboutSidebar/AboutSubSection/AboutSubSection.tsx@@ -2,17 +2,13 @@ import type { ReactNode } from "react";import { Stack, type StackProps, Text, rem } from "metabase/ui";-interface MetricSubSectionProps {+interface AboutSubSectionProps {title: string;children: ReactNode;mt?: StackProps["mt"];}-export function MetricSubSection({- title,- children,- mt,-}: MetricSubSectionProps) {+export function AboutSubSection({ title, children, mt }: AboutSubSectionProps) {return (<Stack gap="sm" mt={mt}><Text fz="sm" lh={rem(16)} fw={400} c="text-secondary">diff --git a/frontend/src/metabase/common/data-studio/components/AboutSidebar/AboutSubSection/index.ts b/frontend/src/metabase/common/data-studio/components/AboutSidebar/AboutSubSection/index.tsnew file mode 100644index 00000000000..3a2dcdc4bea--- /dev/null+++ b/frontend/src/metabase/common/data-studio/components/AboutSidebar/AboutSubSection/index.ts@@ -0,0 +1 @@+export { AboutSubSection } from "./AboutSubSection";diff --git a/frontend/src/metabase/common/data-studio/components/AboutSidebar/CardDescription/CardDescription.tsx b/frontend/src/metabase/common/data-studio/components/AboutSidebar/CardDescription/CardDescription.tsxnew file mode 100644index 00000000000..0bdbde5c556--- /dev/null+++ b/frontend/src/metabase/common/data-studio/components/AboutSidebar/CardDescription/CardDescription.tsx@@ -0,0 +1,70 @@+import { t } from "ttag";++import { useUpdateCardMutation } from "metabase/api";+import { EditableText } from "metabase/common/components/EditableText";+import { Markdown } from "metabase/common/components/Markdown";+import { useMetadataToasts } from "metabase/common/hooks";+import { Box } from "metabase/ui";+import type { Card, CardType } from "metabase-types/api";++interface CardDescriptionProps {+ card: Card;+}++export function CardDescription({ card }: CardDescriptionProps) {+ const [updateCard] = useUpdateCardMutation();+ const { sendSuccessToast, sendErrorToast } = useMetadataToasts();++ const handleChange = async (newValue: string) => {+ const newDescription = newValue.trim();+ const { error } = await updateCard({+ id: card.id,+ description: newDescription.length > 0 ? newDescription : null,+ });+ if (error) {+ sendErrorToast(getErrorMessage(card.type));+ } else {+ sendSuccessToast(getSuccessMessage(card.type));+ }+ };++ return (+ <Box mt="lg" data-testid="about-description">+ {card.can_write ? (+ <EditableText+ initialValue={card.description ?? ""}+ placeholder={t`No description`}+ isMarkdown+ isOptional+ isMultiline+ onChange={handleChange}+ px={0}+ />+ ) : (+ <Markdown>{card.description || t`No description`}</Markdown>+ )}+ </Box>+ );+}++function getSuccessMessage(cardType: CardType) {+ switch (cardType) {+ case "question":+ return t`Question description updated`;+ case "model":+ return t`Model description updated`;+ case "metric":+ return t`Metric description updated`;+ }+}++function getErrorMessage(cardType: CardType) {+ switch (cardType) {+ case "question":+ return t`Failed to update question description`;+ case "model":+ return t`Failed to update model description`;+ case "metric":+ return t`Failed to update metric description`;+ }+}diff --git a/frontend/src/metabase/common/data-studio/components/AboutSidebar/CardDescription/index.ts b/frontend/src/metabase/common/data-studio/components/AboutSidebar/CardDescription/index.tsnew file mode 100644index 00000000000..9f986995e6b--- /dev/null+++ b/frontend/src/metabase/common/data-studio/components/AboutSidebar/CardDescription/index.ts@@ -0,0 +1 @@+export { CardDescription } from "./CardDescription";diff --git a/frontend/src/metabase/common/data-studio/components/AboutSidebar/CardSourceSubSection/CardSourceSubSection.tsx b/frontend/src/metabase/common/data-studio/components/AboutSidebar/CardSourceSubSection/CardSourceSubSection.tsxnew file mode 100644index 00000000000..f10743ee62d--- /dev/null+++ b/frontend/src/metabase/common/data-studio/components/AboutSidebar/CardSourceSubSection/CardSourceSubSection.tsx@@ -0,0 +1,76 @@+import { t } from "ttag";++import { useGetDatabaseQuery, useGetTableQuery } from "metabase/api";+import type { StackProps } from "metabase/ui";+import type { Card, DatabaseId, TableId } from "metabase-types/api";++import { AboutSubSection } from "../AboutSubSection";+import { MetadataCard } from "../MetadataCard";+import { MetadataRow } from "../MetadataRow";+import { MetadataRowLink } from "../MetadataRowLink";++interface CardSourceUrls {+ database?: (databaseId: DatabaseId) => string;+ table?: (databaseId: DatabaseId, tableId: TableId) => string;+}++interface CardSourceSubSectionProps {+ card: Card;+ urls: CardSourceUrls;+ mt?: StackProps["mt"];+}++export function CardSourceSubSection({+ card,+ urls,+ mt,+}: CardSourceSubSectionProps) {+ const { data: database } = useGetDatabaseQuery(+ { id: card.database_id! },+ { skip: !card.database_id },+ );++ const { data: table } = useGetTableQuery(+ { id: card.table_id! },+ { skip: !card.table_id },+ );++ if (!database && !table) {+ return null;+ }++ const databaseUrl = database && urls.database?.(database.id);+ const tableUrl =+ table && card.database_id != null+ ? urls.table?.(card.database_id, table.id)+ : undefined;++ return (+ <AboutSubSection title={t`Source`} mt={mt}>+ <MetadataCard>+ {database && (+ <MetadataRow icon="database">+ {databaseUrl ? (+ <MetadataRowLink to={databaseUrl}>+ {database.name}+ </MetadataRowLink>+ ) : (+ database.name+ )}+ </MetadataRow>+ )}+ {table && (+ <MetadataRow icon="table">+ {tableUrl ? (+ <MetadataRowLink to={tableUrl}>+ {table.display_name || table.name}+ </MetadataRowLink>+ ) : (+ (table.display_name ?? table.name)+ )}+ </MetadataRow>+ )}+ </MetadataCard>+ </AboutSubSection>+ );+}diff --git a/frontend/src/metabase/common/data-studio/components/AboutSidebar/CardSourceSubSection/index.ts b/frontend/src/metabase/common/data-studio/components/AboutSidebar/CardSourceSubSection/index.tsnew file mode 100644index 00000000000..bcac715b31e--- /dev/null+++ b/frontend/src/metabase/common/data-studio/components/AboutSidebar/CardSourceSubSection/index.ts@@ -0,0 +1 @@+export { CardSourceSubSection } from "./CardSourceSubSection";diff --git a/frontend/src/metabase/metrics/pages/MetricAboutPage/MetricAbout/DescriptionSection/MetadataCard.module.css b/frontend/src/metabase/common/data-studio/components/AboutSidebar/MetadataCard/MetadataCard.module.csssimilarity index 73%rename from frontend/src/metabase/metrics/pages/MetricAboutPage/MetricAbout/DescriptionSection/MetadataCard.module.cssrename to frontend/src/metabase/common/data-studio/components/AboutSidebar/MetadataCard/MetadataCard.module.cssindex 28fe0b7b47c..9c30d4a446d 100644--- a/frontend/src/metabase/metrics/pages/MetricAboutPage/MetricAbout/DescriptionSection/MetadataCard.module.css+++ b/frontend/src/metabase/common/data-studio/components/AboutSidebar/MetadataCard/MetadataCard.module.css@@ -28,20 +28,3 @@background: var(--mb-color-border-neutral);pointer-events: none;}--.iconCircle {- position: relative;- border-radius: 100%;- flex-shrink: 0;- box-shadow:- 0 0 0 0.5px rgba(0, 0, 0, 0.1),- 0 1px 3px 0 rgba(0, 0, 0, 0.1);-}--.text {- color: var(--mb-color-core-brand);-}--.link:hover .text {- color: var(--mb-color-text-brand-hover);-}diff --git a/frontend/src/metabase/common/data-studio/components/AboutSidebar/MetadataCard/MetadataCard.tsx b/frontend/src/metabase/common/data-studio/components/AboutSidebar/MetadataCard/MetadataCard.tsxnew file mode 100644index 00000000000..11a63c1ff01--- /dev/null+++ b/frontend/src/metabase/common/data-studio/components/AboutSidebar/MetadataCard/MetadataCard.tsx@@ -0,0 +1,19 @@+import type { ReactNode } from "react";++import { Paper, Stack, rem } from "metabase/ui";++import S from "./MetadataCard.module.css";++interface MetadataCardProps {+ children: ReactNode;+}++export function MetadataCard({ children }: MetadataCardProps) {+ return (+ <Paper className={S.card}>+ <Stack gap={rem(12)} className={S.rows}>+ {children}+ </Stack>+ </Paper>+ );+}diff --git a/frontend/src/metabase/common/data-studio/components/AboutSidebar/MetadataCard/index.ts b/frontend/src/metabase/common/data-studio/components/AboutSidebar/MetadataCard/index.tsnew file mode 100644index 00000000000..de01c57775c--- /dev/null+++ b/frontend/src/metabase/common/data-studio/components/AboutSidebar/MetadataCard/index.ts@@ -0,0 +1 @@+export { MetadataCard } from "./MetadataCard";diff --git a/frontend/src/metabase/common/data-studio/components/AboutSidebar/MetadataRow/MetadataRow.module.css b/frontend/src/metabase/common/data-studio/components/AboutSidebar/MetadataRow/MetadataRow.module.cssnew file mode 100644index 00000000000..e5c1ee7a145--- /dev/null+++ b/frontend/src/metabase/common/data-studio/components/AboutSidebar/MetadataRow/MetadataRow.module.css@@ -0,0 +1,8 @@+.iconCircle {+ position: relative;+ border-radius: 100%;+ flex-shrink: 0;+ box-shadow:+ 0 0 0 0.5px rgba(0, 0, 0, 0.1),+ 0 1px 3px 0 rgba(0, 0, 0, 0.1);+}diff --git a/frontend/src/metabase/metrics/pages/MetricAboutPage/MetricAbout/DescriptionSection/MetadataCard.tsx b/frontend/src/metabase/common/data-studio/components/AboutSidebar/MetadataRow/MetadataRow.tsxsimilarity index 50%rename from frontend/src/metabase/metrics/pages/MetricAboutPage/MetricAbout/DescriptionSection/MetadataCard.tsxrename to frontend/src/metabase/common/data-studio/components/AboutSidebar/MetadataRow/MetadataRow.tsxindex b17df5d3246..d51e20f2e10 100644--- a/frontend/src/metabase/metrics/pages/MetricAboutPage/MetricAbout/DescriptionSection/MetadataCard.tsx+++ b/frontend/src/metabase/common/data-studio/components/AboutSidebar/MetadataRow/MetadataRow.tsx@@ -1,24 +1,9 @@import type { ReactNode } from "react";-import { Link } from "metabase/common/components/Link/Link";-import { Center, Group, Icon, Paper, Stack, Text, rem } from "metabase/ui";+import { Center, Group, Icon, Text, rem } from "metabase/ui";import type { IconName } from "metabase-types/api";-import S from "./MetadataCard.module.css";--interface MetadataCardProps {- children: ReactNode;-}--export function MetadataCard({ children }: MetadataCardProps) {- return (- <Paper className={S.card}>- <Stack gap={rem(12)} className={S.rows}>- {children}- </Stack>- </Paper>- );-}+import S from "./MetadataRow.module.css";interface MetadataRowProps {icon: IconName;@@ -45,19 +30,3 @@ export function MetadataRow({ icon, children, muted }: MetadataRowProps) {</Group>);}--export function MetadataRowLink({- to,- children,-}: {- to: string;- children: ReactNode;-}) {- return (- <Link to={to} className={S.link}>- <Text component="span" fw={600} className={S.text}>- {children}- </Text>- </Link>- );-}diff --git a/frontend/src/metabase/common/data-studio/components/AboutSidebar/MetadataRow/index.ts b/frontend/src/metabase/common/data-studio/components/AboutSidebar/MetadataRow/index.tsnew file mode 100644index 00000000000..9d57bed75f0--- /dev/null+++ b/frontend/src/metabase/common/data-studio/components/AboutSidebar/MetadataRow/index.ts@@ -0,0 +1 @@+export { MetadataRow } from "./MetadataRow";diff --git a/frontend/src/metabase/common/data-studio/components/AboutSidebar/MetadataRowLink/MetadataRowLink.module.css b/frontend/src/metabase/common/data-studio/components/AboutSidebar/MetadataRowLink/MetadataRowLink.module.cssnew file mode 100644index 00000000000..f259c5fb4bd--- /dev/null+++ b/frontend/src/metabase/common/data-studio/components/AboutSidebar/MetadataRowLink/MetadataRowLink.module.css@@ -0,0 +1,7 @@+.text {+ color: var(--mb-color-core-brand);+}++.link:hover .text {+ color: var(--mb-color-text-brand-hover);+}diff --git a/frontend/src/metabase/common/data-studio/components/AboutSidebar/MetadataRowLink/MetadataRowLink.tsx b/frontend/src/metabase/common/data-studio/components/AboutSidebar/MetadataRowLink/MetadataRowLink.tsxnew file mode 100644index 00000000000..d47284a940c--- /dev/null+++ b/frontend/src/metabase/common/data-studio/components/AboutSidebar/MetadataRowLink/MetadataRowLink.tsx@@ -0,0 +1,21 @@+import type { ReactNode } from "react";++import { Link } from "metabase/common/components/Link/Link";+import { Text } from "metabase/ui";++import S from "./MetadataRowLink.module.css";++interface MetadataRowLinkProps {+ to: string;+ children: ReactNode;+}++export function MetadataRowLink({ to, children }: MetadataRowLinkProps) {+ return (+ <Link to={to} className={S.link}>+ <Text component="span" fw={600} className={S.text}>+ {children}+ </Text>+ </Link>+ );+}diff --git a/frontend/src/metabase/common/data-studio/components/AboutSidebar/MetadataRowLink/index.ts b/frontend/src/metabase/common/data-studio/components/AboutSidebar/MetadataRowLink/index.tsnew file mode 100644index 00000000000..9b0bcf5c0e6--- /dev/null+++ b/frontend/src/metabase/common/data-studio/components/AboutSidebar/MetadataRowLink/index.ts@@ -0,0 +1 @@+export { MetadataRowLink } from "./MetadataRowLink";diff --git a/frontend/src/metabase/common/data-studio/components/AboutSidebar/index.ts b/frontend/src/metabase/common/data-studio/components/AboutSidebar/index.tsnew file mode 100644index 00000000000..00bb177e9d7--- /dev/null+++ b/frontend/src/metabase/common/data-studio/components/AboutSidebar/index.ts@@ -0,0 +1 @@+export { AboutSidebar } from "./AboutSidebar";diff --git a/frontend/src/metabase/common/data-studio/components/FeatureEmptyState/FeatureCard/FeatureCard.tsx b/frontend/src/metabase/common/data-studio/components/FeatureEmptyState/FeatureCard/FeatureCard.tsxnew file mode 100644index 00000000000..1416d4b6db2--- /dev/null+++ b/frontend/src/metabase/common/data-studio/components/FeatureEmptyState/FeatureCard/FeatureCard.tsx@@ -0,0 +1,26 @@+import { Group, Icon, Paper, Stack, Text } from "metabase/ui";+import type { IconName } from "metabase-types/api";++interface FeatureCardProps {+ icon: IconName;+ title: string;+ description: string;+}++export function FeatureCard({ icon, title, description }: FeatureCardProps) {+ return (+ <Paper bg="background_page-secondary" p="lg" radius="8px" shadow="none">+ <Group gap="sm" align="flex-start" wrap="nowrap">+ <Icon name={icon} size={16} c="core-brand" style={{ flexShrink: 0 }} />+ <Stack gap="xxs">+ <Text fw="bold" lh="1rem">+ {title}+ </Text>+ <Text c="text-secondary" lh="1rem">+ {description}+ </Text>+ </Stack>+ </Group>+ </Paper>+ );+}diff --git a/frontend/src/metabase/common/data-studio/components/FeatureEmptyState/FeatureCard/index.ts b/frontend/src/metabase/common/data-studio/components/FeatureEmptyState/FeatureCard/index.tsnew file mode 100644index 00000000000..ac3cf5229f7--- /dev/null+++ b/frontend/src/metabase/common/data-studio/components/FeatureEmptyState/FeatureCard/index.ts@@ -0,0 +1 @@+export { FeatureCard } from "./FeatureCard";diff --git a/frontend/src/metabase/common/data-studio/components/FeatureEmptyState/FeatureEmptyState.tsx b/frontend/src/metabase/common/data-studio/components/FeatureEmptyState/FeatureEmptyState.tsxnew file mode 100644index 00000000000..703da2a25c3--- /dev/null+++ b/frontend/src/metabase/common/data-studio/components/FeatureEmptyState/FeatureEmptyState.tsx@@ -0,0 +1,52 @@+import type { ReactNode } from "react";++import { Card, SimpleGrid, Stack, Text, Title } from "metabase/ui";+import type { IconName } from "metabase-types/api";++import { FeatureCard } from "./FeatureCard";++interface FeatureEmptyStateFeature {+ icon: IconName;+ title: string;+ description: string;+}++interface FeatureEmptyStateProps {+ title: string;+ description: ReactNode;+ actions: ReactNode;+ features: FeatureEmptyStateFeature[];+}++export function FeatureEmptyState({+ title,+ description,+ actions,+ features,+}: FeatureEmptyStateProps) {+ return (+ <Card bg="background_page-primary" p={48} maw={640} mx="auto" withBorder>+ <Stack gap="3rem">+ <Stack gap="lg">+ <Stack gap="sm">+ <Title order={3}>{title}</Title>+ <Text c="text-secondary" lh="1.25rem">+ {description}+ </Text>+ </Stack>+ {actions}+ </Stack>+ <SimpleGrid cols={2} spacing="sm">+ {features.map((feature) => (+ <FeatureCard+ key={feature.title}+ icon={feature.icon}+ title={feature.title}+ description={feature.description}+ />+ ))}+ </SimpleGrid>+ </Stack>+ </Card>+ );+}diff --git a/frontend/src/metabase/common/data-studio/components/FeatureEmptyState/index.ts b/frontend/src/metabase/common/data-studio/components/FeatureEmptyState/index.tsnew file mode 100644index 00000000000..472039ba123--- /dev/null+++ b/frontend/src/metabase/common/data-studio/components/FeatureEmptyState/index.ts@@ -0,0 +1 @@+export { FeatureEmptyState } from "./FeatureEmptyState";diff --git a/frontend/src/metabase/data-studio/actions/components/ActionDefinitionContent/ActionDefinitionContent.tsx b/frontend/src/metabase/data-studio/actions/components/ActionDefinitionContent/ActionDefinitionContent.tsxnew file mode 100644index 00000000000..dbe37bac95f--- /dev/null+++ b/frontend/src/metabase/data-studio/actions/components/ActionDefinitionContent/ActionDefinitionContent.tsx@@ -0,0 +1,52 @@+import { useState } from "react";+import { t } from "ttag";++import { Link } from "metabase/common/components/Link";+import { getInitialUiState } from "metabase/querying/editor/components/QueryEditor";+import { Button } from "metabase/ui";+import type { Database, WritebackQueryAction } from "metabase-types/api";++import { ActionEditor } from "../ActionEditor";+import { ActionEditorPane } from "../ActionEditorPane";++type ActionDefinitionContentProps = {+ action: WritebackQueryAction;+ databases: Database[];+ canEdit?: boolean;+ editUrl?: string;+};++export function ActionDefinitionContent({+ action,+ databases,+ canEdit = false,+ editUrl,+}: ActionDefinitionContentProps) {+ const [uiState, setUiState] = useState(getInitialUiState);++ return (+ <ActionEditorPane>+ <ActionEditor+ datasetQuery={action.dataset_query}+ uiState={uiState}+ databases={databases}+ readOnly+ topBarInnerContent={+ canEdit &&+ editUrl != null && (+ <Button+ component={Link}+ to={editUrl}+ size="sm"+ style={{ flexShrink: 0 }}+ >+ {t`Edit definition`}+ </Button>+ )+ }+ onChangeDatasetQuery={() => undefined}+ onChangeUiState={setUiState}+ />+ </ActionEditorPane>+ );+}diff --git a/frontend/src/metabase/data-studio/actions/components/ActionDefinitionContent/index.ts b/frontend/src/metabase/data-studio/actions/components/ActionDefinitionContent/index.tsnew file mode 100644index 00000000000..a645543a723--- /dev/null+++ b/frontend/src/metabase/data-studio/actions/components/ActionDefinitionContent/index.ts@@ -0,0 +1 @@+export { ActionDefinitionContent } from "./ActionDefinitionContent";diff --git a/frontend/src/metabase/data-studio/actions/components/ActionDependenciesContent/ActionDependenciesContent.tsx b/frontend/src/metabase/data-studio/actions/components/ActionDependenciesContent/ActionDependenciesContent.tsxnew file mode 100644index 00000000000..b534da45688--- /dev/null+++ b/frontend/src/metabase/data-studio/actions/components/ActionDependenciesContent/ActionDependenciesContent.tsx@@ -0,0 +1,27 @@+import { PLUGIN_DEPENDENCIES } from "metabase/plugins";+import { Outlet } from "metabase/router";+import { Card } from "metabase/ui";+import type { WritebackQueryAction } from "metabase-types/api";++type ActionDependenciesContentProps = {+ action: WritebackQueryAction;+ baseUrl: string;+};++export function ActionDependenciesContent({+ action,+ baseUrl,+}: ActionDependenciesContentProps) {+ return (+ <PLUGIN_DEPENDENCIES.DependencyGraphPageContext.Provider+ value={{+ baseUrl,+ defaultEntry: { id: action.id, type: "action" },+ }}+ >+ <Card p={0} withBorder flex={1}>+ <Outlet />+ </Card>+ </PLUGIN_DEPENDENCIES.DependencyGraphPageContext.Provider>+ );+}diff --git a/frontend/src/metabase/data-studio/actions/components/ActionDependenciesContent/index.ts b/frontend/src/metabase/data-studio/actions/components/ActionDependenciesContent/index.tsnew file mode 100644index 00000000000..0254dc720cc--- /dev/null+++ b/frontend/src/metabase/data-studio/actions/components/ActionDependenciesContent/index.ts@@ -0,0 +1 @@+export { ActionDependenciesContent } from "./ActionDependenciesContent";diff --git a/frontend/src/metabase/data-studio/actions/pages/ActionFieldsPage/ActionFieldDetails/ActionFieldDetails.tsx b/frontend/src/metabase/data-studio/actions/components/ActionFieldsContent/ActionFieldDetails/ActionFieldDetails.tsxsimilarity index 94%rename from frontend/src/metabase/data-studio/actions/pages/ActionFieldsPage/ActionFieldDetails/ActionFieldDetails.tsxrename to frontend/src/metabase/data-studio/actions/components/ActionFieldsContent/ActionFieldDetails/ActionFieldDetails.tsxindex 27e86f4d104..431607032a3 100644--- a/frontend/src/metabase/data-studio/actions/pages/ActionFieldsPage/ActionFieldDetails/ActionFieldDetails.tsx+++ b/frontend/src/metabase/data-studio/actions/components/ActionFieldsContent/ActionFieldDetails/ActionFieldDetails.tsx@@ -25,14 +25,14 @@ import { getDefaultValueInputType, textToOptions } from "./utils";type ActionFieldDetailsProps = {field: ActionField;- readOnly: boolean;+ disabled: boolean;canChangeFieldType: boolean;onChange: (patch: Partial<FieldSettings>) => void;};export function ActionFieldDetails({field,- readOnly,+ disabled,canChangeFieldType,onChange,}: ActionFieldDetailsProps) {@@ -54,13 +54,13 @@ export function ActionFieldDetails({<BlurTextInputlabel={t`Display name`}value={settings.title}- readOnly={readOnly}+ disabled={disabled}onChange={(title) => onChange({ title })}/><BlurTextarealabel={t`Description`}value={settings.description ?? ""}- readOnly={readOnly}+ disabled={disabled}onChange={(description) => onChange({ description })}/><Stack gap="xs">@@ -81,7 +81,7 @@ export function ActionFieldDetails({value,label: name,}))}- disabled={readOnly || !canChangeFieldType}+ disabled={disabled || !canChangeFieldType}onChange={(value) => {const fieldType = getFieldTypes().find((option) => option.value === value,@@ -96,7 +96,7 @@ export function ActionFieldDetails({label={t`Input type`}value={settings.inputType}data={inputTypes.map(({ value, name }) => ({ value, label: name }))}- readOnly={readOnly}+ disabled={disabled}allowDeselect={false}onChange={(value) => {const inputType = inputTypes.find(@@ -112,7 +112,7 @@ export function ActionFieldDetails({label={t`Options`}description={t`One option per line`}value={(settings.valueOptions ?? []).join("\n")}- readOnly={readOnly}+ disabled={disabled}onChange={(value) =>onChange({valueOptions: textToOptions(value, settings.fieldType),@@ -123,7 +123,7 @@ export function ActionFieldDetails({<BlurTextInputlabel={t`Placeholder`}value={settings.placeholder ?? ""}- readOnly={readOnly}+ disabled={disabled}onChange={(placeholder) => onChange({ placeholder })}/><BlurTextInput@@ -133,7 +133,7 @@ export function ActionFieldDetails({value={settings.defaultValue != null ? String(settings.defaultValue) : ""}- readOnly={readOnly}+ disabled={disabled}onChange={(value) =>onChange({defaultValue: parseDefaultValue(value, settings.fieldType),@@ -146,7 +146,7 @@ export function ActionFieldDetails({label={t`Required`}description={t`People must fill in this field to run the action`}checked={settings.required}- disabled={readOnly}+ disabled={disabled}onChange={(event) =>onChange({ required: event.currentTarget.checked })}@@ -155,7 +155,7 @@ export function ActionFieldDetails({label={t`Show field`}description={t`Hidden fields use their default value`}checked={!settings.hidden}- disabled={readOnly}+ disabled={disabled}onChange={(event) =>onChange({ hidden: !event.currentTarget.checked })}@@ -190,7 +190,7 @@ type BlurInputProps = {placeholder?: string;type?: string;value: string;- readOnly: boolean;+ disabled: boolean;onChange: (value: string) => void;};diff --git a/frontend/src/metabase/data-studio/actions/pages/ActionFieldsPage/ActionFieldDetails/ActionFieldDetails.unit.spec.tsx b/frontend/src/metabase/data-studio/actions/components/ActionFieldsContent/ActionFieldDetails/ActionFieldDetails.unit.spec.tsxsimilarity index 99%rename from frontend/src/metabase/data-studio/actions/pages/ActionFieldsPage/ActionFieldDetails/ActionFieldDetails.unit.spec.tsxrename to frontend/src/metabase/data-studio/actions/components/ActionFieldsContent/ActionFieldDetails/ActionFieldDetails.unit.spec.tsxindex 35345f1249a..9f9d6c6eaf0 100644--- a/frontend/src/metabase/data-studio/actions/pages/ActionFieldsPage/ActionFieldDetails/ActionFieldDetails.unit.spec.tsx+++ b/frontend/src/metabase/data-studio/actions/components/ActionFieldsContent/ActionFieldDetails/ActionFieldDetails.unit.spec.tsx@@ -28,7 +28,7 @@ function setup({ settings, canChangeFieldType = true }: SetupOpts = {}) {}),variableName: "status",}}- readOnly={false}+ disabled={false}canChangeFieldType={canChangeFieldType}onChange={onChange}/>,diff --git a/frontend/src/metabase/data-studio/actions/pages/ActionFieldsPage/ActionFieldDetails/index.ts b/frontend/src/metabase/data-studio/actions/components/ActionFieldsContent/ActionFieldDetails/index.tssimilarity index 100%rename from frontend/src/metabase/data-studio/actions/pages/ActionFieldsPage/ActionFieldDetails/index.tsrename to frontend/src/metabase/data-studio/actions/components/ActionFieldsContent/ActionFieldDetails/index.tsdiff --git a/frontend/src/metabase/data-studio/actions/pages/ActionFieldsPage/ActionFieldDetails/utils.ts b/frontend/src/metabase/data-studio/actions/components/ActionFieldsContent/ActionFieldDetails/utils.tssimilarity index 100%rename from frontend/src/metabase/data-studio/actions/pages/ActionFieldsPage/ActionFieldDetails/utils.tsrename to frontend/src/metabase/data-studio/actions/components/ActionFieldsContent/ActionFieldDetails/utils.tsdiff --git a/frontend/src/metabase/data-studio/actions/pages/ActionFieldsPage/ActionFieldDetails/utils.unit.spec.ts b/frontend/src/metabase/data-studio/actions/components/ActionFieldsContent/ActionFieldDetails/utils.unit.spec.tssimilarity index 100%rename from frontend/src/metabase/data-studio/actions/pages/ActionFieldsPage/ActionFieldDetails/utils.unit.spec.tsrename to frontend/src/metabase/data-studio/actions/components/ActionFieldsContent/ActionFieldDetails/utils.unit.spec.tsdiff --git a/frontend/src/metabase/data-studio/actions/components/ActionFieldsContent/ActionFieldEmptyState/ActionFieldEmptyState.tsx b/frontend/src/metabase/data-studio/actions/components/ActionFieldsContent/ActionFieldEmptyState/ActionFieldEmptyState.tsxnew file mode 100644index 00000000000..66f6f8b6cff--- /dev/null+++ b/frontend/src/metabase/data-studio/actions/components/ActionFieldsContent/ActionFieldEmptyState/ActionFieldEmptyState.tsx@@ -0,0 +1,29 @@+import { t } from "ttag";++import EmptyDashboardBot from "assets/img/dashboard-empty.svg";+import { EmptyState } from "metabase/common/components/EmptyState";+import { Box, rem } from "metabase/ui";++type ActionFieldEmptyStateProps = {+ readOnly: boolean;+};++export function ActionFieldEmptyState({+ readOnly,+}: ActionFieldEmptyStateProps) {+ return (+ <Box maw={rem(320)} p="xxl">+ <EmptyState+ illustrationElement={<img src={EmptyDashboardBot} alt="" />}+ title={+ readOnly ? t`See the action's fields` : t`Edit the action's fields`+ }+ message={+ readOnly+ ? t`Select a field to see its type, input, default value, and more.`+ : t`Select a field to edit its type, input, default value, and more.`+ }+ />+ </Box>+ );+}diff --git a/frontend/src/metabase/data-studio/actions/components/ActionFieldsContent/ActionFieldEmptyState/index.ts b/frontend/src/metabase/data-studio/actions/components/ActionFieldsContent/ActionFieldEmptyState/index.tsnew file mode 100644index 00000000000..fb1be08fe13--- /dev/null+++ b/frontend/src/metabase/data-studio/actions/components/ActionFieldsContent/ActionFieldEmptyState/index.ts@@ -0,0 +1 @@+export { ActionFieldEmptyState } from "./ActionFieldEmptyState";diff --git a/frontend/src/metabase/data-studio/actions/pages/ActionFieldsPage/ActionFieldList/ActionFieldItem/ActionFieldItem.module.css b/frontend/src/metabase/data-studio/actions/components/ActionFieldsContent/ActionFieldList/ActionFieldItem/ActionFieldItem.module.csssimilarity index 100%rename from frontend/src/metabase/data-studio/actions/pages/ActionFieldsPage/ActionFieldList/ActionFieldItem/ActionFieldItem.module.cssrename to frontend/src/metabase/data-studio/actions/components/ActionFieldsContent/ActionFieldList/ActionFieldItem/ActionFieldItem.module.cssdiff --git a/frontend/src/metabase/data-studio/actions/pages/ActionFieldsPage/ActionFieldList/ActionFieldItem/ActionFieldItem.tsx b/frontend/src/metabase/data-studio/actions/components/ActionFieldsContent/ActionFieldList/ActionFieldItem/ActionFieldItem.tsxsimilarity index 100%rename from frontend/src/metabase/data-studio/actions/pages/ActionFieldsPage/ActionFieldList/ActionFieldItem/ActionFieldItem.tsxrename to frontend/src/metabase/data-studio/actions/components/ActionFieldsContent/ActionFieldList/ActionFieldItem/ActionFieldItem.tsxdiff --git a/frontend/src/metabase/data-studio/actions/pages/ActionFieldsPage/ActionFieldList/ActionFieldItem/index.ts b/frontend/src/metabase/data-studio/actions/components/ActionFieldsContent/ActionFieldList/ActionFieldItem/index.tssimilarity index 100%rename from frontend/src/metabase/data-studio/actions/pages/ActionFieldsPage/ActionFieldList/ActionFieldItem/index.tsrename to frontend/src/metabase/data-studio/actions/components/ActionFieldsContent/ActionFieldList/ActionFieldItem/index.tsdiff --git a/frontend/src/metabase/data-studio/actions/pages/ActionFieldsPage/ActionFieldList/ActionFieldItem/utils.ts b/frontend/src/metabase/data-studio/actions/components/ActionFieldsContent/ActionFieldList/ActionFieldItem/utils.tssimilarity index 100%rename from frontend/src/metabase/data-studio/actions/pages/ActionFieldsPage/ActionFieldList/ActionFieldItem/utils.tsrename to frontend/src/metabase/data-studio/actions/components/ActionFieldsContent/ActionFieldList/ActionFieldItem/utils.tsdiff --git a/frontend/src/metabase/data-studio/actions/pages/ActionFieldsPage/ActionFieldList/ActionFieldList.tsx b/frontend/src/metabase/data-studio/actions/components/ActionFieldsContent/ActionFieldList/ActionFieldList.tsxsimilarity index 76%rename from frontend/src/metabase/data-studio/actions/pages/ActionFieldsPage/ActionFieldList/ActionFieldList.tsxrename to frontend/src/metabase/data-studio/actions/components/ActionFieldsContent/ActionFieldList/ActionFieldList.tsxindex 475ee5667f7..1ebcf6f4766 100644--- a/frontend/src/metabase/data-studio/actions/pages/ActionFieldsPage/ActionFieldList/ActionFieldList.tsx+++ b/frontend/src/metabase/data-studio/actions/components/ActionFieldsContent/ActionFieldList/ActionFieldList.tsx@@ -6,28 +6,26 @@ import {SortableList,} from "metabase/common/components/Sortable";import { Stack, Text, Title } from "metabase/ui";-import * as Urls from "metabase/urls";-import type { WritebackActionId } from "metabase-types/api";import type { ActionField } from "../hooks";import { ActionFieldItem } from "./ActionFieldItem";type ActionFieldListProps = {- actionId: WritebackActionId;fields: ActionField[];activeFieldId: string | undefined;readOnly: boolean;+ getFieldUrl: (fieldId: string) => string;onReorder: (fieldIds: string[]) => void;};const getFieldId = (field: ActionField) => field.parameter.id;export function ActionFieldList({- actionId,fields,activeFieldId,readOnly,+ getFieldUrl,onReorder,}: ActionFieldListProps) {const pointerSensor = useSensor(PointerSensor, {@@ -44,9 +42,7 @@ export function ActionFieldList({<Stack gap="xs"><Title order={4}>{t`Fields`}</Title><Text c="text-secondary">- {fields.length > 0- ? t`One field per {{variable}} in the SQL. Drag to reorder the form.`- : t`This action has no variables in its SQL.`}+ {getFieldsDescription(fields.length, isDraggable)}</Text></Stack><Stack gap="md" role="list">@@ -58,7 +54,7 @@ export function ActionFieldList({<ActionFieldItemkey={field.parameter.id}field={field}- href={Urls.dataStudioActionFields(actionId, field.parameter.id)}+ href={getFieldUrl(field.parameter.id)}isActive={field.parameter.id === activeFieldId}isDraggable={isDraggable}/>@@ -69,3 +65,12 @@ export function ActionFieldList({</Stack>);}++function getFieldsDescription(fieldCount: number, isDraggable: boolean) {+ if (fieldCount === 0) {+ return t`This action has no variables in its SQL.`;+ }+ return isDraggable+ ? t`One field per {{variable}} in the SQL. Drag to reorder the form.`+ : t`One field per {{variable}} in the SQL.`;+}diff --git a/frontend/src/metabase/data-studio/actions/pages/ActionFieldsPage/ActionFieldList/index.ts b/frontend/src/metabase/data-studio/actions/components/ActionFieldsContent/ActionFieldList/index.tssimilarity index 100%rename from frontend/src/metabase/data-studio/actions/pages/ActionFieldsPage/ActionFieldList/index.tsrename to frontend/src/metabase/data-studio/actions/components/ActionFieldsContent/ActionFieldList/index.tsdiff --git a/frontend/src/metabase/data-studio/actions/pages/ActionFieldsPage/ActionFieldsPage.module.css b/frontend/src/metabase/data-studio/actions/components/ActionFieldsContent/ActionFieldsContent.module.csssimilarity index 100%rename from frontend/src/metabase/data-studio/actions/pages/ActionFieldsPage/ActionFieldsPage.module.cssrename to frontend/src/metabase/data-studio/actions/components/ActionFieldsContent/ActionFieldsContent.module.cssdiff --git a/frontend/src/metabase/data-studio/actions/components/ActionFieldsContent/ActionFieldsContent.tsx b/frontend/src/metabase/data-studio/actions/components/ActionFieldsContent/ActionFieldsContent.tsxnew file mode 100644index 00000000000..dcae4af5d56--- /dev/null+++ b/frontend/src/metabase/data-studio/actions/components/ActionFieldsContent/ActionFieldsContent.tsx@@ -0,0 +1,95 @@+import { t } from "ttag";++import { ForwardRefLink } from "metabase/common/components/Link";+import { Button, Flex, Group, Icon, Stack, Text } from "metabase/ui";+import type { WritebackQueryAction } from "metabase-types/api";++import { ActionFieldDetails } from "./ActionFieldDetails";+import { ActionFieldEmptyState } from "./ActionFieldEmptyState";+import { ActionFieldList } from "./ActionFieldList";+import S from "./ActionFieldsContent.module.css";+import { useActionFields } from "./hooks";++type ActionFieldsContentProps = {+ action: WritebackQueryAction;+ fieldId: string | undefined;+ canChangeFieldType: boolean;+ getFieldsUrl: (fieldId?: string) => string;+};++export function ActionFieldsContent({+ action,+ fieldId,+ canChangeFieldType,+ getFieldsUrl,+}: ActionFieldsContentProps) {+ const readOnly = !action.can_write;+ const { fields, updateField, reorderFields } = useActionFields(action);+ const field = fields.find((field) => field.parameter.id === fieldId);++ return (+ <Flex className={S.body} flex={1} mih={0}>+ <Stack+ className={S.column}+ flex="8 1 0"+ miw={320}+ maw={640}+ mih={0}+ pl="3.5rem"+ pr="xl"+ >+ <ActionFieldList+ fields={fields}+ activeFieldId={field?.parameter.id}+ readOnly={readOnly}+ getFieldUrl={getFieldsUrl}+ onReorder={reorderFields}+ />+ </Stack>+ {field != null && (+ <Stack+ className={S.column}+ flex="9 1 0"+ miw={320}+ maw={680}+ mih={0}+ px="xl"+ gap={0}+ >+ <Group+ className={S.header}+ justify="space-between"+ pt="xl"+ pb="lg"+ pos="sticky"+ top={0}+ bg="background_page-secondary"+ >+ <Text fw="bold">{t`Field details`}</Text>+ <Button+ variant="subtle"+ color="neutral"+ size="sm"+ component={ForwardRefLink}+ to={getFieldsUrl()}+ aria-label={t`Close`}+ leftSection={<Icon name="close" />}+ />+ </Group>+ <ActionFieldDetails+ key={field.parameter.id}+ field={field}+ disabled={readOnly}+ canChangeFieldType={canChangeFieldType}+ onChange={(patch) => updateField(field.parameter.id, patch)}+ />+ </Stack>+ )}+ {field == null && fields.length > 0 && (+ <Flex align="center" flex="1" justify="center" miw={240}>+ <ActionFieldEmptyState readOnly={readOnly} />+ </Flex>+ )}+ </Flex>+ );+}diff --git a/frontend/src/metabase/data-studio/actions/pages/ActionFieldsPage/hooks.ts b/frontend/src/metabase/data-studio/actions/components/ActionFieldsContent/hooks.tssimilarity index 98%rename from frontend/src/metabase/data-studio/actions/pages/ActionFieldsPage/hooks.tsrename to frontend/src/metabase/data-studio/actions/components/ActionFieldsContent/hooks.tsindex 1160ac732f5..121efe76a99 100644--- a/frontend/src/metabase/data-studio/actions/pages/ActionFieldsPage/hooks.ts+++ b/frontend/src/metabase/data-studio/actions/components/ActionFieldsContent/hooks.ts@@ -16,12 +16,12 @@ import type {WritebackQueryAction,} from "metabase-types/api";-import { useActionQuery } from "../../components/ActionEditor/hooks";import {getFieldSettingsFromQuery,getQueryParameters,setTemplateTagFieldType,} from "../../utils";+import { useActionQuery } from "../ActionEditor/hooks";export type ActionField = {parameter: WritebackParameter;diff --git a/frontend/src/metabase/data-studio/actions/components/ActionFieldsContent/index.ts b/frontend/src/metabase/data-studio/actions/components/ActionFieldsContent/index.tsnew file mode 100644index 00000000000..e2475d8aade--- /dev/null+++ b/frontend/src/metabase/data-studio/actions/components/ActionFieldsContent/index.ts@@ -0,0 +1 @@+export { ActionFieldsContent } from "./ActionFieldsContent";diff --git a/frontend/src/metabase/data-studio/actions/pages/ActionDependenciesPage/ActionDependenciesPage.tsx b/frontend/src/metabase/data-studio/actions/pages/ActionDependenciesPage/ActionDependenciesPage.tsxindex 4e0d3037391..f9f48227595 100644--- a/frontend/src/metabase/data-studio/actions/pages/ActionDependenciesPage/ActionDependenciesPage.tsx+++ b/frontend/src/metabase/data-studio/actions/pages/ActionDependenciesPage/ActionDependenciesPage.tsx@@ -1,10 +1,9 @@import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";import { PageContainer } from "metabase/common/data-studio/components/PageContainer";-import { PLUGIN_DEPENDENCIES } from "metabase/plugins";-import { Outlet } from "metabase/router";-import { Card, Center } from "metabase/ui";+import { Center } from "metabase/ui";import * as Urls from "metabase/urls";+import { ActionDependenciesContent } from "../../components/ActionDependenciesContent";import { ActionHeader } from "../../components/ActionHeader";import { useRouteAction } from "../../hooks/use-route-action";@@ -22,16 +21,10 @@ export function ActionDependenciesPage() {return (<PageContainer data-testid="action-dependencies"><ActionHeader action={action} />- <PLUGIN_DEPENDENCIES.DependencyGraphPageContext.Provider- value={{- baseUrl: Urls.dataStudioActionDependencies(action.id),- defaultEntry: { id: action.id, type: "action" },- }}- >- <Card p={0} withBorder flex={1}>- <Outlet />- </Card>- </PLUGIN_DEPENDENCIES.DependencyGraphPageContext.Provider>+ <ActionDependenciesContent+ action={action}+ baseUrl={Urls.dataStudioActionDependencies(action.id)}+ /></PageContainer>);}diff --git a/frontend/src/metabase/data-studio/actions/pages/ActionFieldsPage/ActionFieldsPage.tsx b/frontend/src/metabase/data-studio/actions/pages/ActionFieldsPage/ActionFieldsPage.tsxindex 68bbbfe0e29..6adfcd07482 100644--- a/frontend/src/metabase/data-studio/actions/pages/ActionFieldsPage/ActionFieldsPage.tsx+++ b/frontend/src/metabase/data-studio/actions/pages/ActionFieldsPage/ActionFieldsPage.tsx@@ -1,24 +1,17 @@-import { t } from "ttag";--import { ForwardRefLink } from "metabase/common/components/Link";import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";import { PageContainer } from "metabase/common/data-studio/components/PageContainer";import { useParams } from "metabase/router";-import { Button, Center, Flex, Group, Icon, Stack, Text } from "metabase/ui";+import { Center } from "metabase/ui";import * as Urls from "metabase/urls";-import type { WritebackQueryAction } from "metabase-types/api";+import { ActionFieldsContent } from "../../components/ActionFieldsContent";import { ActionHeader } from "../../components/ActionHeader";import { useActionDatabases } from "../../hooks/use-action-databases";import { useRouteAction } from "../../hooks/use-route-action";import { canEditActionQuery } from "../../utils";-import { ActionFieldDetails } from "./ActionFieldDetails";-import { ActionFieldList } from "./ActionFieldList";-import S from "./ActionFieldsPage.module.css";-import { useActionFields } from "./hooks";-export function ActionFieldsPage() {+ const { fieldId } = useParams<{ fieldId?: string }>();const {action,isLoading: isLoadingAction,@@ -40,89 +33,17 @@ export function ActionFieldsPage() {);}- return (- <ActionFieldsPageBody- action={action}- canChangeFieldType={canEditActionQuery(action, databases)}- />- );-}--type ActionFieldsPageBodyProps = {- action: WritebackQueryAction;- canChangeFieldType: boolean;-};--function ActionFieldsPageBody({- action,- canChangeFieldType,-}: ActionFieldsPageBodyProps) {- const readOnly = !action.can_write;- const { fieldId } = useParams<{ fieldId?: string }>();- const { fields, updateField, reorderFields } = useActionFields(action);- const field = fields.find((field) => field.parameter.id === fieldId);-return (<PageContainer data-testid="action-fields" gap="lg" px={0} pb={0}><ActionHeader action={action} px="3.5rem" />- <Flex className={S.body} flex={1} mih={0}>- <Stack- className={S.column}- flex="8 1 0"- miw={320}- maw={640}- mih={0}- pl="3.5rem"- pr="xl"- >- <ActionFieldList- actionId={action.id}- fields={fields}- activeFieldId={field?.parameter.id}- readOnly={readOnly}- onReorder={reorderFields}- />- </Stack>- {field != null && (- <Stack- className={S.column}- flex="9 1 0"- miw={320}- maw={680}- mih={0}- px="xl"- gap={0}- >- <Group- className={S.header}- justify="space-between"- pt="xl"- pb="lg"- pos="sticky"- top={0}- bg="background_page-secondary"- >- <Text fw="bold">{t`Field details`}</Text>- <Button- variant="subtle"- color="neutral"- size="sm"- component={ForwardRefLink}- to={Urls.dataStudioActionFields(action.id)}- aria-label={t`Close`}- leftSection={<Icon name="close" />}- />- </Group>- <ActionFieldDetails- key={field.parameter.id}- field={field}- readOnly={readOnly}- canChangeFieldType={canChangeFieldType}- onChange={(patch) => updateField(field.parameter.id, patch)}- />- </Stack>- )}- </Flex>+ <ActionFieldsContent+ action={action}+ fieldId={fieldId}+ canChangeFieldType={canEditActionQuery(action, databases)}+ getFieldsUrl={(fieldId) =>+ Urls.dataStudioActionFields(action.id, fieldId)+ }+ /></PageContainer>);}diff --git a/frontend/src/metabase/data-studio/actions/pages/ActionFieldsPage/ActionFieldsPage.unit.spec.tsx b/frontend/src/metabase/data-studio/actions/pages/ActionFieldsPage/ActionFieldsPage.unit.spec.tsxindex 73d70039662..503207ed12b 100644--- a/frontend/src/metabase/data-studio/actions/pages/ActionFieldsPage/ActionFieldsPage.unit.spec.tsx+++ b/frontend/src/metabase/data-studio/actions/pages/ActionFieldsPage/ActionFieldsPage.unit.spec.tsx@@ -23,9 +23,10 @@ import { ActionFieldsPage } from "./ActionFieldsPage";type SetupOpts = {action: WritebackQueryAction;database: Database;+ fieldId?: string;};-function setup({ action, database }: SetupOpts) {+function setup({ action, database, fieldId = "status" }: SetupOpts) {setupActionEndpoints(action);setupDatabaseListEndpoint([database]);setupCollectionByIdEndpoint({@@ -33,16 +34,22 @@ function setup({ action, database }: SetupOpts) {});renderWithProviders(- <Route- path="/data-studio/data-actions/:actionId/fields/:fieldId"- element={<ActionFieldsPage />}- />,+ <>+ <Route+ path="/data-studio/data-actions/:actionId/fields"+ element={<ActionFieldsPage />}+ />+ <Route+ path="/data-studio/data-actions/:actionId/fields/:fieldId"+ element={<ActionFieldsPage />}+ />+ </>,{storeInitialState: createMockState({entities: createMockEntitiesState({ databases: [database] }),}),withRouter: true,- initialRoute: `/data-studio/data-actions/${action.id}/fields/status`,+ initialRoute: `/data-studio/data-actions/${action.id}/fields${fieldId ? `/${fieldId}` : ""}`,},);}@@ -62,6 +69,27 @@ const DATASET_QUERY = createMockNativeDatasetQuery({}),});+const TWO_VARIABLE_DATASET_QUERY = createMockNativeDatasetQuery({+ database: 1,+ native: createMockNativeQuery({+ query: "UPDATE orders SET status = {{status}} WHERE id = {{id}}",+ "template-tags": {+ status: createMockTemplateTag({+ id: "status",+ name: "status",+ "display-name": "Status",+ type: "text",+ }),+ id: createMockTemplateTag({+ id: "id",+ name: "id",+ "display-name": "ID",+ type: "number",+ }),+ },+ }),+});+describe("ActionFieldsPage", () => {it("should let a user who can edit the action change every field setting", async () => {setup({@@ -77,9 +105,7 @@ describe("ActionFieldsPage", () => {}),});- expect(await screen.findByLabelText("Display name")).not.toHaveAttribute(- "readonly",- );+ expect(await screen.findByLabelText("Display name")).toBeEnabled();expect(screen.getByRole("radio", { name: "Number" })).toBeEnabled();});@@ -97,9 +123,7 @@ describe("ActionFieldsPage", () => {}),});- expect(await screen.findByLabelText("Display name")).toHaveAttribute(- "readonly",- );+ expect(await screen.findByLabelText("Display name")).toBeDisabled();expect(screen.getByRole("radio", { name: "Number" })).toBeDisabled();});@@ -117,9 +141,7 @@ describe("ActionFieldsPage", () => {}),});- expect(await screen.findByLabelText("Display name")).not.toHaveAttribute(- "readonly",- );+ expect(await screen.findByLabelText("Display name")).toBeEnabled();expect(screen.getByRole("radio", { name: "Number" })).toBeDisabled();});@@ -137,9 +159,88 @@ describe("ActionFieldsPage", () => {}),});- expect(await screen.findByLabelText("Display name")).not.toHaveAttribute(- "readonly",- );+ expect(await screen.findByLabelText("Display name")).toBeEnabled();expect(screen.getByRole("radio", { name: "Number" })).toBeDisabled();});++ it("should tell a user who can edit the action that fields can be reordered", async () => {+ setup({+ action: createMockQueryAction({+ database_id: 1,+ dataset_query: TWO_VARIABLE_DATASET_QUERY,+ can_write: true,+ }),+ database: createMockDatabase({+ id: 1,+ native_permissions: "write",+ settings: { "database-enable-actions": true },+ }),+ });++ expect(+ await screen.findByText(+ "One field per {{variable}} in the SQL. Drag to reorder the form.",+ ),+ ).toBeInTheDocument();+ });++ it("should not mention reordering to a user who can't edit the action", async () => {+ setup({+ action: createMockQueryAction({+ database_id: 1,+ dataset_query: TWO_VARIABLE_DATASET_QUERY,+ can_write: false,+ }),+ database: createMockDatabase({+ id: 1,+ native_permissions: "write",+ settings: { "database-enable-actions": true },+ }),+ });++ expect(+ await screen.findByText("One field per {{variable}} in the SQL."),+ ).toBeInTheDocument();+ });++ it("asks a user who can edit the action to select a field", async () => {+ setup({+ action: createMockQueryAction({+ database_id: 1,+ dataset_query: DATASET_QUERY,+ can_write: true,+ }),+ database: createMockDatabase({+ id: 1,+ native_permissions: "write",+ settings: { "database-enable-actions": true },+ }),+ fieldId: "",+ });++ expect(+ await screen.findByText("Edit the action's fields"),+ ).toBeInTheDocument();+ expect(screen.queryByLabelText("Display name")).not.toBeInTheDocument();+ });++ it("asks a user who can't edit the action to select a field to see it", async () => {+ setup({+ action: createMockQueryAction({+ database_id: 1,+ dataset_query: DATASET_QUERY,+ can_write: false,+ }),+ database: createMockDatabase({+ id: 1,+ native_permissions: "write",+ settings: { "database-enable-actions": true },+ }),+ fieldId: "",+ });++ expect(+ await screen.findByText("See the action's fields"),+ ).toBeInTheDocument();+ });});diff --git a/frontend/src/metabase/data-studio/actions/pages/ActionQueryPage/ActionQueryPage.tsx b/frontend/src/metabase/data-studio/actions/pages/ActionQueryPage/ActionQueryPage.tsxindex ddbf2cc493d..6100fdafdbb 100644--- a/frontend/src/metabase/data-studio/actions/pages/ActionQueryPage/ActionQueryPage.tsx+++ b/frontend/src/metabase/data-studio/actions/pages/ActionQueryPage/ActionQueryPage.tsx@@ -4,7 +4,6 @@ import { t } from "ttag";import { useUpdateActionMutation } from "metabase/api";import { getErrorMessage } from "metabase/api/utils";import { LeaveRouteConfirmModal } from "metabase/common/components/LeaveConfirmModal";-import { Link } from "metabase/common/components/Link";import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";import { PageContainer } from "metabase/common/data-studio/components/PageContainer";import { PaneHeaderActions } from "metabase/common/data-studio/components/PaneHeader";@@ -12,10 +11,11 @@ import { useMetadataToasts } from "metabase/common/hooks";import { hasNativeWritePermissions } from "metabase/common/utils/database";import { getInitialUiState } from "metabase/querying/editor/components/QueryEditor";import { type Location, useLocation, useNavigate } from "metabase/router";-import { Button, Center } from "metabase/ui";+import { Center } from "metabase/ui";import * as Urls from "metabase/urls";import type { Database, WritebackQueryAction } from "metabase-types/api";+import { ActionDefinitionContent } from "../../components/ActionDefinitionContent";import { ActionEditor } from "../../components/ActionEditor";import { ActionEditorPane } from "../../components/ActionEditorPane";import { ActionHeader } from "../../components/ActionHeader";@@ -83,33 +83,15 @@ function ActionDefinitionPage({databases,canEditQuery,}: ActionDefinitionPageProps) {- const [uiState, setUiState] = useState(getInitialUiState);-return (<PageContainer data-testid="action-definition"><ActionHeader action={action} />- <ActionEditorPane>- <ActionEditor- datasetQuery={action.dataset_query}- uiState={uiState}- databases={databases}- readOnly- topBarInnerContent={- canEditQuery && (- <Button- component={Link}- to={Urls.dataStudioActionEdit(action.id)}- size="sm"- style={{ flexShrink: 0 }}- >- {t`Edit definition`}- </Button>- )- }- onChangeDatasetQuery={() => undefined}- onChangeUiState={setUiState}- />- </ActionEditorPane>+ <ActionDefinitionContent+ action={action}+ databases={databases}+ canEdit={canEditQuery}+ editUrl={Urls.dataStudioActionEdit(action.id)}+ /></PageContainer>);}diff --git a/frontend/src/metabase/data-studio/app/pages/DataStudioLayout/DataStudioLayout.tsx b/frontend/src/metabase/data-studio/app/pages/DataStudioLayout/DataStudioLayout.tsxindex d53beb5f3bc..b0ed3a1004d 100644--- a/frontend/src/metabase/data-studio/app/pages/DataStudioLayout/DataStudioLayout.tsx+++ b/frontend/src/metabase/data-studio/app/pages/DataStudioLayout/DataStudioLayout.tsx@@ -5,6 +5,7 @@ import DataStudioLogo from "assets/img/data-studio-logo.svg";import { useHasTokenFeature } from "metabase/common/hooks";import {canAccessDataModel as canAccessDataModelSelector,+ getUserIsAdmin,useUserKeyValue,} from "metabase/current-user";import { useDataStudioSettings } from "metabase/data-studio/settings/hooks/use-data-studio-settings";@@ -13,7 +14,7 @@ import {AreaTab,AreaTabGroup,} from "metabase/nav/components/AreaLayout";-import { PLUGIN_REMOTE_SYNC } from "metabase/plugins";+import { PLUGIN_DATA_APPS, PLUGIN_REMOTE_SYNC } from "metabase/plugins";import { useSelector } from "metabase/redux";import { Outlet, useLocation } from "metabase/router";import { useSetting } from "metabase/settings";@@ -36,6 +37,7 @@ export function DataStudioLayout() {const { pathname } = useLocation();const canAccessDataModel = useSelector(canAccessDataModelSelector);const canAccessTransforms = useSelector(canAccessTransformsSelector);+ const isAdmin = useSelector(getUserIsAdmin);const hasDirtyChanges = PLUGIN_REMOTE_SYNC.useHasLibraryDirtyChanges();const hasTransformDirtyChanges =PLUGIN_REMOTE_SYNC.useHasTransformDirtyChanges();@@ -147,6 +149,15 @@ export function DataStudioLayout() {) : null}/>+ {PLUGIN_DATA_APPS.isEnabled && isAdmin && (+ <AreaTab+ label={t`Data apps`}+ icon="app"+ to={Urls.dataStudioDataApps()}+ isSelected={currentTab === "data-apps"}+ showLabel={isNavbarOpened}+ />+ )}<AreaTablabel={t`Glossary`}icon="glossary"diff --git a/frontend/src/metabase/data-studio/app/pages/DataStudioLayout/utils.ts b/frontend/src/metabase/data-studio/app/pages/DataStudioLayout/utils.tsindex e1a2254e1ad..96876569d5a 100644--- a/frontend/src/metabase/data-studio/app/pages/DataStudioLayout/utils.ts+++ b/frontend/src/metabase/data-studio/app/pages/DataStudioLayout/utils.ts@@ -7,6 +7,7 @@ type TabName =| "dashboards"| "snippets"| "actions"+ | "data-apps"| "transforms"| "dependencies"| "schema-viewer"@@ -30,6 +31,8 @@ export const getCurrentTab = (pathname: string): TabName => {return "snippets";case pathname.startsWith(Urls.dataStudioActions()):return "actions";+ case pathname.startsWith(Urls.dataStudioDataApps()):+ return "data-apps";case pathname.startsWith(Urls.dataStudioLibrary()):return "library";case pathname.startsWith(Urls.dataStudioDashboards()):diff --git a/frontend/src/metabase/data-studio/app/pages/DataStudioLayout/utils.unit.spec.ts b/frontend/src/metabase/data-studio/app/pages/DataStudioLayout/utils.unit.spec.tsindex 044690d25f0..4b195f3ae8e 100644--- a/frontend/src/metabase/data-studio/app/pages/DataStudioLayout/utils.unit.spec.ts+++ b/frontend/src/metabase/data-studio/app/pages/DataStudioLayout/utils.unit.spec.ts@@ -22,6 +22,8 @@ describe("getCurrentTab", () => {${"/data-studio/snippets/12"} | ${"snippets"}${"/data-studio/actions"} | ${"actions"}${"/data-studio/actions/34/run"} | ${"actions"}+ ${"/data-studio/apps"} | ${"data-apps"}+ ${"/data-studio/apps/sales/actions/3/fields"} | ${"data-apps"}${"/data-studio/transforms/runs"} | ${"transforms"}${"/data-studio/transforms/runs?page=2"} | ${"transforms"}${"/data-studio/transforms"} | ${"transforms"}diff --git a/frontend/src/metabase/data-studio/routes.tsx b/frontend/src/metabase/data-studio/routes.tsxindex 28d07069f4f..e7f2ac70208 100644--- a/frontend/src/metabase/data-studio/routes.tsx+++ b/frontend/src/metabase/data-studio/routes.tsx@@ -2,6 +2,7 @@ import { NotFound } from "metabase/common/components/ErrorPages";import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";import { canAccessDataModel, useUserKeyValue } from "metabase/current-user";import {+ PLUGIN_DATA_APPS,PLUGIN_DEPENDENCIES,PLUGIN_LIBRARY,PLUGIN_SCHEMA_VIEWER,@@ -112,6 +113,8 @@ export function getDataStudioRoutes(IsAdmin: RouteComponent) {{getDataStudioGlossaryRoutes()}{getDataStudioSnippetRoutes()}{getDataStudioActionRoutes()}+ {PLUGIN_DATA_APPS.isEnabled &&+ PLUGIN_DATA_APPS.getDataStudioRoutes(IsAdmin)}{getDataStudioSettingsRoutes()}{PLUGIN_LIBRARY.isEnabled ? (PLUGIN_LIBRARY.getDataStudioLibraryRoutes(IsAdmin)diff --git a/frontend/src/metabase/metrics/pages/MetricAboutPage/MetricAbout/DescriptionSection/DescriptionSection.tsx b/frontend/src/metabase/metrics/pages/MetricAboutPage/MetricAbout/DescriptionSection/DescriptionSection.tsxindex edf97bce5c6..6e04a7c7395 100644--- a/frontend/src/metabase/metrics/pages/MetricAboutPage/MetricAbout/DescriptionSection/DescriptionSection.tsx+++ b/frontend/src/metabase/metrics/pages/MetricAboutPage/MetricAbout/DescriptionSection/DescriptionSection.tsx@@ -1,14 +1,13 @@import { jt, msgid, ngettext, t } from "ttag";-import {- useGetDatabaseQuery,- useGetTableQuery,- useUpdateCardMutation,-} from "metabase/api";-import { DateTime } from "metabase/common/components/DateTime";-import { EditableText } from "metabase/common/components/EditableText";-import { Markdown } from "metabase/common/components/Markdown";-import { useMetadataToasts } from "metabase/common/hooks";+import { AboutSidebar } from "metabase/common/data-studio/components/AboutSidebar";+import { AboutHeader } from "metabase/common/data-studio/components/AboutSidebar/AboutHeader";+import { AboutSubSection } from "metabase/common/data-studio/components/AboutSidebar/AboutSubSection";+import { CardDescription } from "metabase/common/data-studio/components/AboutSidebar/CardDescription";+import { CardSourceSubSection } from "metabase/common/data-studio/components/AboutSidebar/CardSourceSubSection";+import { MetadataCard } from "metabase/common/data-studio/components/AboutSidebar/MetadataCard";+import { MetadataRow } from "metabase/common/data-studio/components/AboutSidebar/MetadataRow";+import { MetadataRowLink } from "metabase/common/data-studio/components/AboutSidebar/MetadataRowLink";import type { MetricUrls } from "metabase/common/metrics/types";import {getUserIsAdmin,@@ -16,12 +15,7 @@ import {} from "metabase/current-user";import { PLUGIN_DEPENDENCIES } from "metabase/plugins";import { useSelector } from "metabase/redux";-import { Box, Stack, Text, Tooltip } from "metabase/ui";-import { getRelativeTime } from "metabase/utils/time-dayjs";-import type { Card as CardApiType, CardType } from "metabase-types/api";--import { MetadataCard, MetadataRow, MetadataRowLink } from "./MetadataCard";-import { MetricSubSection } from "./MetricSubSection";+import type { Card as CardApiType } from "metabase-types/api";interface DescriptionSectionProps {card: CardApiType;@@ -29,117 +23,27 @@ interface DescriptionSectionProps {}export function DescriptionSection({ card, urls }: DescriptionSectionProps) {- const [updateCard] = useUpdateCardMutation();- const { sendSuccessToast, sendErrorToast } = useMetadataToasts();-const canSeeRelationships =useSelector((state) => getUserIsAdmin(state) || getUserIsEntitledAnalyst(state),) && PLUGIN_DEPENDENCIES.isEnabled;- const { data: database } = useGetDatabaseQuery(- { id: card.database_id! },- { skip: !card.database_id },- );-- const { data: table } = useGetTableQuery(- { id: card.table_id! },- { skip: !card.table_id },- );-const { dependentsCount, dependenciesCount } =PLUGIN_DEPENDENCIES.useGetDependenciesCount({id: Number(card.id),type: "card",});- const handleChange = async (newValue: string) => {- const newDescription = newValue.trim();- const { error } = await updateCard({- id: card.id,- description: newDescription.length > 0 ? newDescription : null,- });- if (error) {- sendErrorToast(getErrorMessage(card.type));- } else {- sendSuccessToast(getSuccessMessage(card.type));- }- };-- const hasSource = Boolean(database || table);const dependenciesUrl = urls.dependencies(card.id);- const databaseUrl = database && urls.database?.(database.id);- const tableUrl =- table && card.database_id != null- ? urls.table?.(card.database_id, table.id)- : undefined;return (- <Stack- p="lg"- gap={0}- align="stretch"- data-testid="metric-description-sidebar"- >- <Text fz="lg" fw={700}>{t`About`}</Text>- <Tooltip label={<DateTime value={card.updated_at} />} offset={8}>- <Text- size="sm"- c="text-secondary"- w="fit-content"- mt="sm"- data-testid="metric-last-updated"- >- {t`Last updated ${getRelativeTime(card.updated_at)}`}- </Text>- </Tooltip>- <Box mt="lg" data-testid="metric-description-section">- {card.can_write ? (- <EditableText- initialValue={card.description ?? ""}- placeholder={t`No description`}- isMarkdown- isOptional- isMultiline- onChange={handleChange}- px={0}- />- ) : (- <Markdown>{card.description || t`No description`}</Markdown>- )}- </Box>-- {hasSource && (- <MetricSubSection title={t`Source`} mt="xxl">- <MetadataCard>- {database && (- <MetadataRow icon="database">- {databaseUrl ? (- <MetadataRowLink to={databaseUrl}>- {database.name}- </MetadataRowLink>- ) : (- database.name- )}- </MetadataRow>- )}- {table && (- <MetadataRow icon="table">- {tableUrl ? (- <MetadataRowLink to={tableUrl}>- {table.display_name || table.name}- </MetadataRowLink>- ) : (- (table.display_name ?? table.name)- )}- </MetadataRow>- )}- </MetadataCard>- </MetricSubSection>- )}+ <AboutSidebar data-testid="metric-description-sidebar">+ <AboutHeader updatedAt={card.updated_at} />+ <CardDescription card={card} />+ <CardSourceSubSection card={card} urls={urls} mt="xxl" />{canSeeRelationships && (- <MetricSubSection title={t`Relationships`} mt="xxl">+ <AboutSubSection title={t`Relationships`} mt="xxl"><MetadataCard><MetadataRow icon="dependencies" muted={dependenciesCount === 0}>{dependenciesCount > 0 ? (@@ -168,30 +72,8 @@ export function DescriptionSection({ card, urls }: DescriptionSectionProps) {: t`No charts use this metric`}</MetadataRow></MetadataCard>- </MetricSubSection>+ </AboutSubSection>)}- </Stack>+ </AboutSidebar>);}--function getSuccessMessage(cardType: CardType) {- switch (cardType) {- case "question":- return t`Question description updated`;- case "model":- return t`Model description updated`;- case "metric":- return t`Metric description updated`;- }-}--function getErrorMessage(cardType: CardType) {- switch (cardType) {- case "question":- return t`Failed to update question description`;- case "model":- return t`Failed to update model description`;- case "metric":- return t`Failed to update metric description`;- }-}diff --git a/frontend/src/metabase/metrics/pages/MetricAboutPage/MetricAbout/DescriptionSection/DescriptionSection.unit.spec.tsx b/frontend/src/metabase/metrics/pages/MetricAboutPage/MetricAbout/DescriptionSection/DescriptionSection.unit.spec.tsxindex 4f70a7bcedb..4e00ee3f2db 100644--- a/frontend/src/metabase/metrics/pages/MetricAboutPage/MetricAbout/DescriptionSection/DescriptionSection.unit.spec.tsx+++ b/frontend/src/metabase/metrics/pages/MetricAboutPage/MetricAbout/DescriptionSection/DescriptionSection.unit.spec.tsx@@ -121,7 +121,7 @@ describe("DescriptionSection", () => {it("renders the About heading and last-updated subline", async () => {setup();expect(screen.getByText("About")).toBeInTheDocument();- expect(await screen.findByTestId("metric-last-updated")).toHaveTextContent(+ expect(await screen.findByTestId("about-last-updated")).toHaveTextContent(/Last updated/,);});diff --git a/frontend/src/metabase/palette/hooks/useCommandPaletteBasicActions.tsx b/frontend/src/metabase/palette/hooks/useCommandPaletteBasicActions.tsxindex 0b5c3f60d36..89e9666c8a2 100644--- a/frontend/src/metabase/palette/hooks/useCommandPaletteBasicActions.tsx+++ b/frontend/src/metabase/palette/hooks/useCommandPaletteBasicActions.tsx@@ -16,6 +16,7 @@ import {} from "metabase/current-user";import { getHasDatabaseWithActionsEnabled } from "metabase/databases/utils/predicates";import { openEmbedJsWizard } from "metabase/embedding/store/embed-setup-modal";+import { PLUGIN_DATA_APPS } from "metabase/plugins";import { useDispatch, useSelector } from "metabase/redux";import { closeNavbar, openDiagnostics } from "metabase/redux/app";import type { ModalName } from "metabase/redux/store/modal";@@ -251,12 +252,14 @@ export const useCommandPaletteBasicActions = ({dispatch(openEmbedJsWizard());},});+ }+ if (isAdmin && PLUGIN_DATA_APPS.isEnabled) {actions.push({id: "navigate-data-apps",section: "basic",icon: "app",- perform: () => navigate(Urls.dataAppsSettings()),+ perform: () => navigate(Urls.dataStudioDataApps()),});}diff --git a/frontend/src/metabase/palette/shortcuts/global-shortcuts.unit.spec.tsx b/frontend/src/metabase/palette/shortcuts/global-shortcuts.unit.spec.tsxindex ce2504f2926..195318573f0 100644--- a/frontend/src/metabase/palette/shortcuts/global-shortcuts.unit.spec.tsx+++ b/frontend/src/metabase/palette/shortcuts/global-shortcuts.unit.spec.tsx@@ -11,6 +11,7 @@ import { createMockState } from "__support__/state";import { renderWithProviders, waitFor } from "__support__/ui";import * as Analytics from "metabase/analytics";import { Palette } from "metabase/palette/components/Palette";+import { PLUGIN_DATA_APPS } from "metabase/plugins";import { Route } from "metabase/router";import {createMockCollection,@@ -75,7 +76,6 @@ describe("global keyboard shortcuts", () => {["g a", "ga", "/admin/settings"],["g s", "gs", "/data-studio"],["g p", "gp", `/collection/${PERSONAL_COLLECTION_ID}`],- ["g Shift+a", "g{Shift>}a{/Shift}", "/admin/settings/apps"],])("%s navigates to %s", async (_name, keys, pathname) => {const { router } = await setup();@@ -91,6 +91,28 @@ describe("global keyboard shortcuts", () => {});});+ it("navigates to Data Studio's data apps when data apps are enabled", async () => {+ jest.replaceProperty(PLUGIN_DATA_APPS, "isEnabled", true);+ const { router } = await setup();++ await waitFor(async () => {+ if (router?.location.pathname !== "/data-studio/apps") {+ await userEvent.keyboard("g{Shift>}a{/Shift}");+ }+ expect(router?.location.pathname).toBe("/data-studio/apps");+ });+ });++ it("does not navigate to data apps when they are not enabled", async () => {+ const { router } = await setup();++ await userEvent.keyboard("g{Shift>}a{/Shift}");+ expect(router?.location.pathname).toBe("/");+ await userEvent.keyboard("gt");++ await waitFor(() => expect(router?.location.pathname).toBe("/trash"));+ });+it("does not navigate to Data Studio for users without access", async () => {const { router } = await setup({ isAdmin: false });diff --git a/frontend/src/metabase/plugins/index.ts b/frontend/src/metabase/plugins/index.tsindex c16d1bbaff2..0fc5c22760c 100644--- a/frontend/src/metabase/plugins/index.ts+++ b/frontend/src/metabase/plugins/index.ts@@ -155,7 +155,9 @@ export {export {PLUGIN_TRANSFORMS,PLUGIN_TRANSFORMS_PYTHON,+ PLUGIN_TRANSFORMS_TESTING,type TransformsPlugin,+ type TransformsTestingPlugin,type PythonTransformEditorProps,type PythonTransformSourceSectionProps,type PythonTransformSourceValidationResult,diff --git a/frontend/src/metabase/plugins/oss/data-apps.ts b/frontend/src/metabase/plugins/oss/data-apps.tsindex c88a360c649..4794b31c15e 100644--- a/frontend/src/metabase/plugins/oss/data-apps.ts+++ b/frontend/src/metabase/plugins/oss/data-apps.ts@@ -7,16 +7,14 @@ import { definePluginSlot } from "../slot";export type DataAppsPlugin = {isEnabled: boolean;getRoutes: () => ReactNode | null;- ManageDataAppsPage: ComponentType;- ManageDataAppGroupsPage: ComponentType;+ getDataStudioRoutes: (IsAdmin: ComponentType) => ReactNode | null;MainNavbarSection: ComponentType<{ onItemSelect: () => void }>;};const getDefaultPluginDataApps = (): DataAppsPlugin => ({isEnabled: false,getRoutes: () => null,- ManageDataAppsPage: PluginPlaceholder,- ManageDataAppGroupsPage: PluginPlaceholder,+ getDataStudioRoutes: () => null,MainNavbarSection: PluginPlaceholder,});diff --git a/frontend/src/metabase/plugins/oss/transforms.ts b/frontend/src/metabase/plugins/oss/transforms.tsindex c405d0a86ef..c3081c7d2a6 100644--- a/frontend/src/metabase/plugins/oss/transforms.ts+++ b/frontend/src/metabase/plugins/oss/transforms.ts@@ -63,6 +63,11 @@ export type PythonTransformsPlugin = {sharedLibImportPath: string;};+export type TransformsTestingPlugin = {+ isEnabled: boolean;+ getTransformTestRoutes: () => ReactNode;+};+const getDefaultPluginTransforms = (): TransformsPlugin => ({isEnabled: true, // transforms are enabled by default in OSSTransformsUpsellPage: PluginPlaceholder,@@ -87,3 +92,12 @@ const getDefaultPluginTransformsPython = (): PythonTransformsPlugin => ({export const PLUGIN_TRANSFORMS_PYTHON = definePluginSlot(getDefaultPluginTransformsPython,);++const getDefaultPluginTransformsTesting = (): TransformsTestingPlugin => ({+ isEnabled: false,+ getTransformTestRoutes: () => null,+});++export const PLUGIN_TRANSFORMS_TESTING = definePluginSlot(+ getDefaultPluginTransformsTesting,+);diff --git a/frontend/src/metabase/transforms/pages/RunListPage/RunFilterBar/FilterFieldSet/FilterFieldSet.module.css b/frontend/src/metabase/transforms/components/FilterFieldSet/FilterFieldSet.module.csssimilarity index 100%rename from frontend/src/metabase/transforms/pages/RunListPage/RunFilterBar/FilterFieldSet/FilterFieldSet.module.cssrename to frontend/src/metabase/transforms/components/FilterFieldSet/FilterFieldSet.module.cssdiff --git a/frontend/src/metabase/transforms/pages/RunListPage/RunFilterBar/FilterFieldSet/FilterFieldSet.tsx b/frontend/src/metabase/transforms/components/FilterFieldSet/FilterFieldSet.tsxsimilarity index 100%rename from frontend/src/metabase/transforms/pages/RunListPage/RunFilterBar/FilterFieldSet/FilterFieldSet.tsxrename to frontend/src/metabase/transforms/components/FilterFieldSet/FilterFieldSet.tsxdiff --git a/frontend/src/metabase/transforms/components/FilterFieldSet/index.ts b/frontend/src/metabase/transforms/components/FilterFieldSet/index.tsnew file mode 100644index 00000000000..ce0d53b07b7--- /dev/null+++ b/frontend/src/metabase/transforms/components/FilterFieldSet/index.ts@@ -0,0 +1 @@+export { FilterFieldSet } from "./FilterFieldSet";diff --git a/frontend/src/metabase/transforms/components/RunButton/RunButton.tsx b/frontend/src/metabase/transforms/components/RunButton/RunButton.tsxindex 91c51b8c791..e33e72c2108 100644--- a/frontend/src/metabase/transforms/components/RunButton/RunButton.tsx+++ b/frontend/src/metabase/transforms/components/RunButton/RunButton.tsx@@ -30,7 +30,7 @@ const RECENT_TIMEOUT = 5000;type RunButtonProps = {id: TransformId | TransformJobId | undefined;- run: TransformRun | null | undefined;+ run: Pick<TransformRun, "status"> | null | undefined;isDisabled?: boolean;isLoading?: boolean;allowCancellation?: boolean;@@ -126,7 +126,7 @@ export const RunButton = forwardRef(function RunButton(});type RunButtonOpts = {- run: TransformRun | null | undefined;+ run: Pick<TransformRun, "status"> | null | undefined;isRecent: boolean;isLoading: boolean;isDisabled: boolean;diff --git a/frontend/src/metabase/transforms/pages/RunListPage/RunFilterBar/RunMethodFilterWidget/RunMethodFilterWidget.tsx b/frontend/src/metabase/transforms/components/RunMethodFilterWidget/RunMethodFilterWidget.tsxsimilarity index 97%rename from frontend/src/metabase/transforms/pages/RunListPage/RunFilterBar/RunMethodFilterWidget/RunMethodFilterWidget.tsxrename to frontend/src/metabase/transforms/components/RunMethodFilterWidget/RunMethodFilterWidget.tsxindex 638881f986c..cfa53bf3f7f 100644--- a/frontend/src/metabase/transforms/pages/RunListPage/RunFilterBar/RunMethodFilterWidget/RunMethodFilterWidget.tsx+++ b/frontend/src/metabase/transforms/components/RunMethodFilterWidget/RunMethodFilterWidget.tsx@@ -14,7 +14,7 @@ import {} from "metabase/ui";import type { TransformRunMethod } from "metabase-types/api";-import { FILTER_WIDGET_MIN_WIDTH } from "../../../../constants";+import { FILTER_WIDGET_MIN_WIDTH } from "../../constants";import { FilterFieldSet } from "../FilterFieldSet";const RUN_METHODS: TransformRunMethod[] = ["manual", "cron"];diff --git a/frontend/src/metabase/transforms/components/RunMethodFilterWidget/index.ts b/frontend/src/metabase/transforms/components/RunMethodFilterWidget/index.tsnew file mode 100644index 00000000000..a6fc429d550--- /dev/null+++ b/frontend/src/metabase/transforms/components/RunMethodFilterWidget/index.ts@@ -0,0 +1 @@+export { RunMethodFilterWidget } from "./RunMethodFilterWidget";diff --git a/frontend/src/metabase/transforms/components/RunStatus/RunStatus.tsx b/frontend/src/metabase/transforms/components/RunStatus/RunStatus.tsxindex 84f99dc1e5a..637c39e2025 100644--- a/frontend/src/metabase/transforms/components/RunStatus/RunStatus.tsx+++ b/frontend/src/metabase/transforms/components/RunStatus/RunStatus.tsx@@ -8,7 +8,7 @@ import { parseTimestampWithTimezone } from "../../utils";import { RunInfo } from "../RunInfo";type RunStatusSectionProps = {- run: TransformRun | null;+ run: Pick<TransformRun, "status" | "end_time" | "message"> | null;neverRunMessage: string;runInfo?: React.ReactNode;};diff --git a/frontend/src/metabase/transforms/components/SidebarResizableBox/SidebarResizableBox.module.css b/frontend/src/metabase/transforms/components/SidebarResizableBox/SidebarResizableBox.module.cssdeleted file mode 100644index 5a7b5e9487b..00000000000--- a/frontend/src/metabase/transforms/components/SidebarResizableBox/SidebarResizableBox.module.css+++ /dev/null@@ -1,3 +0,0 @@-.resizableBox {- display: flex;-}diff --git a/frontend/src/metabase/transforms/components/SidebarResizableBox/SidebarResizableBox.tsx b/frontend/src/metabase/transforms/components/SidebarResizableBox/SidebarResizableBox.tsxdeleted file mode 100644index 8d4237c7441..00000000000--- a/frontend/src/metabase/transforms/components/SidebarResizableBox/SidebarResizableBox.tsx+++ /dev/null@@ -1,41 +0,0 @@-import type { ReactNode } from "react";-import { ResizableBox } from "react-resizable";--import { ResizeHandle } from "metabase/common/components/ResizeHandle";--import S from "./SidebarResizableBox.module.css";--const MIN_SIDEBAR_WIDTH = 400;-const DEFAULT_SIDEBAR_WIDTH = 512;--type SidebarResizableBoxProps = {- containerWidth: number;- children?: ReactNode;- onResizeStart: () => void;- onResizeStop: () => void;-};--export function SidebarResizableBox({- containerWidth,- children,- onResizeStart,- onResizeStop,-}: SidebarResizableBoxProps) {- const maxSidebarWidth = Math.max(containerWidth / 2, MIN_SIDEBAR_WIDTH);-- return (- <ResizableBox- className={S.resizableBox}- width={DEFAULT_SIDEBAR_WIDTH}- minConstraints={[MIN_SIDEBAR_WIDTH, 0]}- maxConstraints={[maxSidebarWidth, 0]}- axis="x"- resizeHandles={["w"]}- handle={<ResizeHandle handleAxis="w" />}- onResizeStart={onResizeStart}- onResizeStop={onResizeStop}- >- {children}- </ResizableBox>- );-}diff --git a/frontend/src/metabase/transforms/pages/RunListPage/RunFilterBar/StatusFilterWidget/StatusFilterWidget.tsx b/frontend/src/metabase/transforms/components/StatusFilterWidget/StatusFilterWidget.tsxsimilarity index 58%rename from frontend/src/metabase/transforms/pages/RunListPage/RunFilterBar/StatusFilterWidget/StatusFilterWidget.tsxrename to frontend/src/metabase/transforms/components/StatusFilterWidget/StatusFilterWidget.tsxindex 6e91564c687..d597529fe9f 100644--- a/frontend/src/metabase/transforms/pages/RunListPage/RunFilterBar/StatusFilterWidget/StatusFilterWidget.tsx+++ b/frontend/src/metabase/transforms/components/StatusFilterWidget/StatusFilterWidget.tsx@@ -11,33 +11,31 @@ import {Popover,Stack,} from "metabase/ui";-import type { TransformRunStatus } from "metabase-types/api";-import { FILTER_WIDGET_MIN_WIDTH } from "../../../../constants";-import { formatStatus } from "../../../../utils";+import { FILTER_WIDGET_MIN_WIDTH } from "../../constants";import { FilterFieldSet } from "../FilterFieldSet";-const STATUSES: TransformRunStatus[] = [- "started",- "succeeded",- "failed",- "timeout",-];+export type StatusFilterOption<T extends string> = {+ value: T;+ label: string;+};-type StatusFilterWidgetProps = {+type StatusFilterWidgetProps<T extends string> = {label: string;- statuses: TransformRunStatus[];- onChange: (statuses: TransformRunStatus[]) => void;+ statuses: T[];+ options: StatusFilterOption<T>[];+ onChange: (statuses: T[]) => void;};-export function StatusFilterWidget({+export function StatusFilterWidget<T extends string>({label,statuses,+ options,onChange,-}: StatusFilterWidgetProps) {+}: StatusFilterWidgetProps<T>) {const [isOpened, { toggle, close }] = useDisclosure();- const handleSubmit = (statuses: TransformRunStatus[]) => {+ const handleSubmit = (statuses: T[]) => {close();onChange(statuses);};@@ -52,45 +50,60 @@ export function StatusFilterWidget({<FilterFieldSetlabel={label}icon="check_filled"- displayValue={getDisplayValue(statuses)}+ displayValue={getDisplayValue(statuses, options)}onClick={toggle}onRemove={handleRemove}/></Popover.Target><Popover.Dropdown>- <StatusFilterForm statuses={statuses} onSubmit={handleSubmit} />+ <StatusFilterForm+ statuses={statuses}+ options={options}+ onSubmit={handleSubmit}+ /></Popover.Dropdown></Popover>);}-function getDisplayValue(statuses: TransformRunStatus[]) {+function getDisplayValue<T extends string>(+ statuses: T[],+ options: StatusFilterOption<T>[],+) {const count = statuses.length;switch (count) {case 0:return null;case 1:- return formatStatus(statuses[0]);+ return (+ options.find((option) => option.value === statuses[0])?.label ??+ statuses[0]+ );default:return ngettext(msgid`${count} status`, `${count} statuses`, count);}}-type StatusFilterForm = {- statuses: TransformRunStatus[];- onSubmit: (statuses: TransformRunStatus[]) => void;+type StatusFilterFormProps<T extends string> = {+ statuses: T[];+ options: StatusFilterOption<T>[];+ onSubmit: (statuses: T[]) => void;};-function StatusFilterForm({+function StatusFilterForm<T extends string>({statuses: initialStatuses,+ options,onSubmit,-}: StatusFilterForm) {+}: StatusFilterFormProps<T>) {const [statuses, setStatuses] = useState(initialStatuses);const isValid = statuses.length > 0;const handleChange = (values: string[]) => {- // Unjustified type cast. FIXME- setStatuses(values as TransformRunStatus[]);+ setStatuses(+ options+ .filter((option) => values.includes(option.value))+ .map((option) => option.value),+ );};const handleSubmit = (event: FormEvent) => {@@ -104,11 +117,11 @@ function StatusFilterForm({<Box component="form" miw={FILTER_WIDGET_MIN_WIDTH} onSubmit={handleSubmit}><Checkbox.Group value={statuses} onChange={handleChange}><Stack p="lg">- {STATUSES.map((status) => (+ {options.map((option) => (<Checkbox- key={status}- value={status}- label={formatStatus(status)}+ key={option.value}+ value={option.value}+ label={option.label}/>))}</Stack>diff --git a/frontend/src/metabase/transforms/components/StatusFilterWidget/index.ts b/frontend/src/metabase/transforms/components/StatusFilterWidget/index.tsnew file mode 100644index 00000000000..6aac1219b5e--- /dev/null+++ b/frontend/src/metabase/transforms/components/StatusFilterWidget/index.ts@@ -0,0 +1 @@+export { StatusFilterWidget } from "./StatusFilterWidget";diff --git a/frontend/src/metabase/transforms/pages/RunListPage/RunFilterBar/TimeFilterWidget/TimeFilterWidget.tsx b/frontend/src/metabase/transforms/components/TimeFilterWidget/TimeFilterWidget.tsxsimilarity index 100%rename from frontend/src/metabase/transforms/pages/RunListPage/RunFilterBar/TimeFilterWidget/TimeFilterWidget.tsxrename to frontend/src/metabase/transforms/components/TimeFilterWidget/TimeFilterWidget.tsxdiff --git a/frontend/src/metabase/transforms/components/TimeFilterWidget/index.ts b/frontend/src/metabase/transforms/components/TimeFilterWidget/index.tsnew file mode 100644index 00000000000..65bd76d6d1a--- /dev/null+++ b/frontend/src/metabase/transforms/components/TimeFilterWidget/index.ts@@ -0,0 +1 @@+export { TimeFilterWidget } from "./TimeFilterWidget";diff --git a/frontend/src/metabase/transforms/pages/RunListPage/RunFilterBar/TransformFilterWidget/TransformFilterWidget.tsx b/frontend/src/metabase/transforms/components/TransformFilterWidget/TransformFilterWidget.tsxsimilarity index 99%rename from frontend/src/metabase/transforms/pages/RunListPage/RunFilterBar/TransformFilterWidget/TransformFilterWidget.tsxrename to frontend/src/metabase/transforms/components/TransformFilterWidget/TransformFilterWidget.tsxindex 2996633a802..153d95b9515 100644--- a/frontend/src/metabase/transforms/pages/RunListPage/RunFilterBar/TransformFilterWidget/TransformFilterWidget.tsx+++ b/frontend/src/metabase/transforms/components/TransformFilterWidget/TransformFilterWidget.tsx@@ -17,7 +17,7 @@ import type { Transform, TransformId } from "metabase-types/api";import {FILTER_WIDGET_MAX_HEIGHT,FILTER_WIDGET_MIN_WIDTH,-} from "../../../../constants";+} from "../../constants";import { FilterFieldSet } from "../FilterFieldSet";type TransformFilterWidgetProps = {diff --git a/frontend/src/metabase/transforms/components/TransformFilterWidget/index.ts b/frontend/src/metabase/transforms/components/TransformFilterWidget/index.tsnew file mode 100644index 00000000000..2d0b8413996--- /dev/null+++ b/frontend/src/metabase/transforms/components/TransformFilterWidget/index.ts@@ -0,0 +1 @@+export { TransformFilterWidget } from "./TransformFilterWidget";diff --git a/frontend/src/metabase/transforms/components/TransformHeader/TransformTabs.tsx b/frontend/src/metabase/transforms/components/TransformHeader/TransformTabs.tsxindex dec915e1a3b..ef3fa6e7633 100644--- a/frontend/src/metabase/transforms/components/TransformHeader/TransformTabs.tsx+++ b/frontend/src/metabase/transforms/components/TransformHeader/TransformTabs.tsx@@ -7,6 +7,7 @@ import {import {PLUGIN_DEPENDENCIES,PLUGIN_TRANSFORMS_PYTHON,+ PLUGIN_TRANSFORMS_TESTING,} from "metabase/plugins";import * as Urls from "metabase/urls";import type { Transform, TransformId } from "metabase-types/api";@@ -41,6 +42,15 @@ function getTabs(id: TransformId): PillTab[] {},];+ if (PLUGIN_TRANSFORMS_TESTING.isEnabled) {+ const testListUrl = Urls.transformTestList(id);+ tabs.push({+ label: t`Tests`,+ to: testListUrl,+ isSelected: (pathname: string) => pathname.startsWith(testListUrl),+ });+ }+if (PLUGIN_TRANSFORMS_PYTHON.shouldShowInspectTab) {tabs.push({label: t`Inspect`,diff --git a/frontend/src/metabase/transforms/constants.ts b/frontend/src/metabase/transforms/constants.tsindex 80009d023b9..9152fb5e208 100644--- a/frontend/src/metabase/transforms/constants.ts+++ b/frontend/src/metabase/transforms/constants.ts@@ -1,6 +1,7 @@import { t } from "ttag";import { isCypressActive } from "metabase/env";+import type { TransformRunStatus } from "metabase-types/api";export const NAME_MAX_LENGTH = 254;@@ -29,3 +30,10 @@ export const TARGET_STRATEGY_OPTIONS = [},},];++export const RUN_STATUS_FILTER_VALUES: TransformRunStatus[] = [+ "started",+ "succeeded",+ "failed",+ "timeout",+];diff --git a/frontend/src/metabase/transforms/pages/JobRunListPage/JobRunSidebar/JobRunSidebar.tsx b/frontend/src/metabase/transforms/pages/JobRunListPage/JobRunSidebar/JobRunSidebar.tsxindex d44b1a0ec6f..552a1bb937b 100644--- a/frontend/src/metabase/transforms/pages/JobRunListPage/JobRunSidebar/JobRunSidebar.tsx+++ b/frontend/src/metabase/transforms/pages/JobRunListPage/JobRunSidebar/JobRunSidebar.tsx@@ -4,7 +4,7 @@ import { t } from "ttag";import { useListJobRunTransformRunsQuery } from "metabase/api";import { ListEmptyState } from "metabase/common/components/ListEmptyState";import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";-import { SidebarResizableBox } from "metabase/transforms/components/SidebarResizableBox";+import { SidebarResizableBox } from "metabase/common/components/SidebarResizableBox";import { POLLING_INTERVAL } from "metabase/transforms/constants";import {ActionIcon,diff --git a/frontend/src/metabase/transforms/pages/RunListPage/RunFilterBar/FilterFieldSet/index.ts b/frontend/src/metabase/transforms/pages/RunListPage/RunFilterBar/FilterFieldSet/index.tsdeleted file mode 100644index 275fcac125f..00000000000--- a/frontend/src/metabase/transforms/pages/RunListPage/RunFilterBar/FilterFieldSet/index.ts+++ /dev/null@@ -1 +0,0 @@-export * from "./FilterFieldSet";diff --git a/frontend/src/metabase/transforms/pages/RunListPage/RunFilterBar/RunFilterBar.tsx b/frontend/src/metabase/transforms/pages/RunListPage/RunFilterBar/RunFilterBar.tsxindex b171174192b..95e486e48e1 100644--- a/frontend/src/metabase/transforms/pages/RunListPage/RunFilterBar/RunFilterBar.tsx+++ b/frontend/src/metabase/transforms/pages/RunListPage/RunFilterBar/RunFilterBar.tsx@@ -1,6 +1,11 @@import { t } from "ttag";import type { RelativeIntervalDirection } from "metabase/querying/common/types";+import { RunMethodFilterWidget } from "metabase/transforms/components/RunMethodFilterWidget";+import { StatusFilterWidget } from "metabase/transforms/components/StatusFilterWidget";+import { TimeFilterWidget } from "metabase/transforms/components/TimeFilterWidget";+import { TransformFilterWidget } from "metabase/transforms/components/TransformFilterWidget";+import { getRunStatusOptions } from "metabase/transforms/utils";import { Group } from "metabase/ui";import type {Transform,@@ -13,11 +18,7 @@ import type {import type { TransformRunFilterOptions } from "../types";-import { RunMethodFilterWidget } from "./RunMethodFilterWidget";-import { StatusFilterWidget } from "./StatusFilterWidget";import { TagFilterWidget } from "./TagFilterWidget";-import { TimeFilterWidget } from "./TimeFilterWidget";-import { TransformFilterWidget } from "./TransformFilterWidget";const PAST_INTERVAL_DIRECTIONS: RelativeIntervalDirection[] = ["past",@@ -83,6 +84,7 @@ export function RunFilterBar({<StatusFilterWidgetlabel={t`Status`}statuses={filterOptions.statuses ?? []}+ options={getRunStatusOptions()}onChange={handleStatusesChange}/><RunMethodFilterWidgetdiff --git a/frontend/src/metabase/transforms/pages/RunListPage/RunFilterBar/RunMethodFilterWidget/index.ts b/frontend/src/metabase/transforms/pages/RunListPage/RunFilterBar/RunMethodFilterWidget/index.tsdeleted file mode 100644index 5e7e2f5a5b6..00000000000--- a/frontend/src/metabase/transforms/pages/RunListPage/RunFilterBar/RunMethodFilterWidget/index.ts+++ /dev/null@@ -1 +0,0 @@-export * from "./RunMethodFilterWidget";diff --git a/frontend/src/metabase/transforms/pages/RunListPage/RunFilterBar/StatusFilterWidget/index.ts b/frontend/src/metabase/transforms/pages/RunListPage/RunFilterBar/StatusFilterWidget/index.tsdeleted file mode 100644index b6afd926fed..00000000000--- a/frontend/src/metabase/transforms/pages/RunListPage/RunFilterBar/StatusFilterWidget/index.ts+++ /dev/null@@ -1 +0,0 @@-export * from "./StatusFilterWidget";diff --git a/frontend/src/metabase/transforms/pages/RunListPage/RunFilterBar/TagFilterWidget/TagFilterWidget.tsx b/frontend/src/metabase/transforms/pages/RunListPage/RunFilterBar/TagFilterWidget/TagFilterWidget.tsxindex ba3035f400a..2ae4414e0c0 100644--- a/frontend/src/metabase/transforms/pages/RunListPage/RunFilterBar/TagFilterWidget/TagFilterWidget.tsx+++ b/frontend/src/metabase/transforms/pages/RunListPage/RunFilterBar/TagFilterWidget/TagFilterWidget.tsx@@ -2,6 +2,7 @@ import { useDisclosure } from "@mantine/hooks";import { type FormEvent, useState } from "react";import { msgid, ngettext, t } from "ttag";+import { FilterFieldSet } from "metabase/transforms/components/FilterFieldSet";import {Box,Button,@@ -17,7 +18,6 @@ import {FILTER_WIDGET_MAX_HEIGHT,FILTER_WIDGET_MIN_WIDTH,} from "../../../../constants";-import { FilterFieldSet } from "../FilterFieldSet";type TagFilterWidgetProps = {label: string;diff --git a/frontend/src/metabase/transforms/pages/RunListPage/RunFilterBar/TimeFilterWidget/index.ts b/frontend/src/metabase/transforms/pages/RunListPage/RunFilterBar/TimeFilterWidget/index.tsdeleted file mode 100644index 4495d7dbd11..00000000000--- a/frontend/src/metabase/transforms/pages/RunListPage/RunFilterBar/TimeFilterWidget/index.ts+++ /dev/null@@ -1 +0,0 @@-export * from "./TimeFilterWidget";diff --git a/frontend/src/metabase/transforms/pages/RunListPage/RunFilterBar/TransformFilterWidget/index.ts b/frontend/src/metabase/transforms/pages/RunListPage/RunFilterBar/TransformFilterWidget/index.tsdeleted file mode 100644index 2c382ab98b9..00000000000--- a/frontend/src/metabase/transforms/pages/RunListPage/RunFilterBar/TransformFilterWidget/index.ts+++ /dev/null@@ -1 +0,0 @@-export * from "./TransformFilterWidget";diff --git a/frontend/src/metabase/transforms/pages/RunListPage/RunSidebar/RunSidebar.tsx b/frontend/src/metabase/transforms/pages/RunListPage/RunSidebar/RunSidebar.tsxindex d3386d193b1..3d7af15bb53 100644--- a/frontend/src/metabase/transforms/pages/RunListPage/RunSidebar/RunSidebar.tsx+++ b/frontend/src/metabase/transforms/pages/RunListPage/RunSidebar/RunSidebar.tsx@@ -1,7 +1,7 @@import { memo } from "react";+import { SidebarResizableBox } from "metabase/common/components/SidebarResizableBox";import { ErrorSection } from "metabase/transforms/components/ErrorSection";-import { SidebarResizableBox } from "metabase/transforms/components/SidebarResizableBox";import { Stack } from "metabase/ui";import type { TransformRun } from "metabase-types/api";diff --git a/frontend/src/metabase/transforms/pages/TransformGraphRunListPage/TransformGraphRunFilterBar/TransformGraphRunFilterBar.tsx b/frontend/src/metabase/transforms/pages/TransformGraphRunListPage/TransformGraphRunFilterBar/TransformGraphRunFilterBar.tsxindex 19ca92f6376..9686031ac25 100644--- a/frontend/src/metabase/transforms/pages/TransformGraphRunListPage/TransformGraphRunFilterBar/TransformGraphRunFilterBar.tsx+++ b/frontend/src/metabase/transforms/pages/TransformGraphRunListPage/TransformGraphRunFilterBar/TransformGraphRunFilterBar.tsx@@ -1,10 +1,11 @@import { t } from "ttag";import type { RelativeIntervalDirection } from "metabase/querying/common/types";-import { RunMethodFilterWidget } from "metabase/transforms/pages/RunListPage/RunFilterBar/RunMethodFilterWidget";-import { StatusFilterWidget } from "metabase/transforms/pages/RunListPage/RunFilterBar/StatusFilterWidget";-import { TimeFilterWidget } from "metabase/transforms/pages/RunListPage/RunFilterBar/TimeFilterWidget";-import { TransformFilterWidget } from "metabase/transforms/pages/RunListPage/RunFilterBar/TransformFilterWidget";+import { RunMethodFilterWidget } from "metabase/transforms/components/RunMethodFilterWidget";+import { StatusFilterWidget } from "metabase/transforms/components/StatusFilterWidget";+import { TimeFilterWidget } from "metabase/transforms/components/TimeFilterWidget";+import { TransformFilterWidget } from "metabase/transforms/components/TransformFilterWidget";+import { getRunStatusOptions } from "metabase/transforms/utils";import { Group } from "metabase/ui";import type {Transform,@@ -86,6 +87,7 @@ export function TransformGraphRunFilterBar({<StatusFilterWidgetlabel={t`Status`}statuses={filterOptions.statuses ?? []}+ options={getRunStatusOptions()}onChange={handleStatusesChange}/><RunMethodFilterWidgetdiff --git a/frontend/src/metabase/transforms/pages/TransformGraphRunListPage/TransformGraphRunFilterBar/TypeFilterWidget.tsx b/frontend/src/metabase/transforms/pages/TransformGraphRunListPage/TransformGraphRunFilterBar/TypeFilterWidget.tsxindex f825b10f61b..91f13aaab38 100644--- a/frontend/src/metabase/transforms/pages/TransformGraphRunListPage/TransformGraphRunFilterBar/TypeFilterWidget.tsx+++ b/frontend/src/metabase/transforms/pages/TransformGraphRunListPage/TransformGraphRunFilterBar/TypeFilterWidget.tsx@@ -2,8 +2,8 @@ import { useDisclosure } from "@mantine/hooks";import { type FormEvent, useState } from "react";import { t } from "ttag";+import { FilterFieldSet } from "metabase/transforms/components/FilterFieldSet";import { FILTER_WIDGET_MIN_WIDTH } from "metabase/transforms/constants";-import { FilterFieldSet } from "metabase/transforms/pages/RunListPage/RunFilterBar/FilterFieldSet";import {Box,Button,diff --git a/frontend/src/metabase/transforms/pages/TransformGraphRunListPage/TransformGraphRunSidebar/TransformGraphRunSidebar.tsx b/frontend/src/metabase/transforms/pages/TransformGraphRunListPage/TransformGraphRunSidebar/TransformGraphRunSidebar.tsxindex d67566e726f..139f28e91f5 100644--- a/frontend/src/metabase/transforms/pages/TransformGraphRunListPage/TransformGraphRunSidebar/TransformGraphRunSidebar.tsx+++ b/frontend/src/metabase/transforms/pages/TransformGraphRunListPage/TransformGraphRunSidebar/TransformGraphRunSidebar.tsx@@ -15,9 +15,9 @@ import { ConfirmModal } from "metabase/common/components/ConfirmModal";import { ForwardRefLink } from "metabase/common/components/Link";import { ListEmptyState } from "metabase/common/components/ListEmptyState";import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";+import { SidebarResizableBox } from "metabase/common/components/SidebarResizableBox";import { useMetadataToasts } from "metabase/common/hooks";import { PLUGIN_DEPENDENCIES } from "metabase/plugins";-import { SidebarResizableBox } from "metabase/transforms/components/SidebarResizableBox";import { POLLING_INTERVAL } from "metabase/transforms/constants";import { isActiveRunStatus } from "metabase/transforms/utils";import {diff --git a/frontend/src/metabase/transforms/routes.tsx b/frontend/src/metabase/transforms/routes.tsxindex 32204b1de10..c08cc5d173a 100644--- a/frontend/src/metabase/transforms/routes.tsx+++ b/frontend/src/metabase/transforms/routes.tsx@@ -2,6 +2,7 @@ import {PLUGIN_DEPENDENCIES,PLUGIN_REPLACEMENT,PLUGIN_TRANSFORMS_PYTHON,+ PLUGIN_TRANSFORMS_TESTING,} from "metabase/plugins";import { Route } from "metabase/router";@@ -154,6 +155,7 @@ export function getDataStudioTransformRoutes() {<Route path=":transformId/run" lazy={transformRunPage} /><Route path=":transformId/settings" lazy={transformSettingsPage} /><Route path=":transformId/indexes" lazy={transformIndexesPage} />+ {PLUGIN_TRANSFORMS_TESTING.getTransformTestRoutes()}{PLUGIN_TRANSFORMS_PYTHON.getInspectorRoutes()}{PLUGIN_DEPENDENCIES.isEnabled && (<Routediff --git a/frontend/src/metabase/transforms/utils.ts b/frontend/src/metabase/transforms/utils.tsindex 8ae688f7bb6..656bf0cb828 100644--- a/frontend/src/metabase/transforms/utils.ts+++ b/frontend/src/metabase/transforms/utils.ts@@ -16,6 +16,8 @@ import type {TransformSource,} from "metabase-types/api";+import { RUN_STATUS_FILTER_VALUES } from "./constants";+export function parseTimestampWithTimezone(timestamp: string,systemTimezone: string | undefined,@@ -50,6 +52,16 @@ export function formatStatus(status: TransformRunStatus | null) {}}+export function getRunStatusOptions(): {+ value: TransformRunStatus;+ label: string;+}[] {+ return RUN_STATUS_FILTER_VALUES.map((status) => ({+ value: status,+ label: formatStatus(status),+ }));+}+export function formatRunMethod(trigger: TransformRunMethod) {switch (trigger) {case "manual":diff --git a/frontend/src/metabase/urls/admin.ts b/frontend/src/metabase/urls/admin.tsindex 4c0e956f8fc..43132e63ecc 100644--- a/frontend/src/metabase/urls/admin.ts+++ b/frontend/src/metabase/urls/admin.ts@@ -4,6 +4,7 @@ import type {CustomVizPluginId,DatabaseId,FieldId,+ GroupId,SchemaName,SegmentId,TableId,@@ -56,6 +57,10 @@ export function unsubscribeUser(user: Pick<BaseUser, "id" | "tenant_id">) {: `${getTenantsBasePath()}/people/${user.id}/unsubscribe`;}+export function adminGroup(groupId: GroupId) {+ return `/admin/people/groups/${groupId}`;+}+// TODO: move to EE urlsexport function newDatabase() {diff --git a/frontend/src/metabase/urls/data-apps.ts b/frontend/src/metabase/urls/data-apps.tsindex f816fb69245..0d903b74d89 100644--- a/frontend/src/metabase/urls/data-apps.ts+++ b/frontend/src/metabase/urls/data-apps.ts@@ -1,3 +1,5 @@+import type { CardId, WritebackActionId } from "metabase-types/api";+/*** Canonical data-app URLs. `DATA_APP_URL_SEGMENT` is the single source of* truth for the `apps` path segment; the page, admin, and iframe-embed URLs@@ -26,7 +28,58 @@ export function dataApp(name: string) {return `${DATA_APP_ROOT_URL}/${encodeURIComponent(name)}`;}-/** Admin page listing the data apps: `/admin/settings/apps`. */-export function dataAppsSettings() {- return `/admin/settings/${DATA_APP_URL_SEGMENT}`;+export function dataStudioDataApps() {+ return `/data-studio/${DATA_APP_URL_SEGMENT}`;+}++export function dataStudioDataApp(name: string) {+ return `${dataStudioDataApps()}/${encodeURIComponent(name)}`;+}++export function dataStudioDataAppQuestions(name: string) {+ return `${dataStudioDataApp(name)}/questions`;+}++export function dataStudioDataAppActions(name: string) {+ return `${dataStudioDataApp(name)}/actions`;+}++export function dataStudioDataAppQuestion(name: string, cardId: CardId) {+ return `${dataStudioDataAppQuestions(name)}/${cardId}`;+}++export function dataStudioDataAppQuestionDependencies(+ name: string,+ cardId: CardId,+) {+ return `${dataStudioDataAppQuestion(name, cardId)}/dependencies`;+}++export function dataStudioDataAppPermissions(name: string) {+ return `${dataStudioDataApp(name)}/permissions`;+}++export function dataStudioDataAppAction(+ name: string,+ actionId: WritebackActionId,+) {+ return `${dataStudioDataAppActions(name)}/${actionId}`;+}++export function dataStudioDataAppActionFields(+ name: string,+ actionId: WritebackActionId,+ fieldId?: string,+) {+ const fieldsUrl = `${dataStudioDataAppAction(name, actionId)}/fields`;+ return fieldId != null+ ? `${fieldsUrl}/${encodeURIComponent(fieldId)}`+ : fieldsUrl;+}++export function dataStudioDataAppActionDependencies(+ name: string,+ actionId: WritebackActionId,+) {+ return `${dataStudioDataAppAction(name, actionId)}/dependencies`;}diff --git a/frontend/src/metabase/urls/transforms.ts b/frontend/src/metabase/urls/transforms.tsindex 89d9ba62cbb..b9a5b31251b 100644--- a/frontend/src/metabase/urls/transforms.ts+++ b/frontend/src/metabase/urls/transforms.ts@@ -16,6 +16,8 @@ import type {TransformRunSortColumn,TransformRunStatus,TransformTagId,+ TransformTestId,+ TransformTestRunStatus,} from "metabase-types/api";const TRANSFORMS_ROOT_URL = `/data-studio/transforms`;@@ -80,6 +82,47 @@ export function transformIndexes(transformId: TransformId) {return `${TRANSFORMS_ROOT_URL}/${transformId}/indexes`;}+export function transformTestList(transformId: TransformId) {+ return `${TRANSFORMS_ROOT_URL}/${transformId}/tests`;+}++export function transformTest(+ transformId: TransformId,+ testId: TransformTestId,+) {+ return `${TRANSFORMS_ROOT_URL}/${transformId}/tests/${testId}`;+}++export type TransformTestRunListParams = {+ page?: number;+ statuses?: TransformTestRunStatus[];+ startTime?: string;+ endTime?: string;+};++export function transformTestRuns(+ transformId: TransformId,+ testId: TransformTestId,+ { page, statuses, startTime, endTime }: TransformTestRunListParams = {},+) {+ const searchParams = new URLSearchParams();+ if (page != null) {+ searchParams.set("page", String(page));+ }+ statuses?.forEach((status) => {+ searchParams.append("statuses", status);+ });+ if (startTime != null) {+ searchParams.set("start-time", startTime);+ }+ if (endTime != null) {+ searchParams.set("end-time", endTime);+ }+ const queryString = searchParams.toString();+ const baseUrl = `${transformTest(transformId, testId)}/runs`;+ return queryString.length > 0 ? `${baseUrl}?${queryString}` : baseUrl;+}+export function transformDependencies(transformId: TransformId) {return `${TRANSFORMS_ROOT_URL}/${transformId}/dependencies`;}diff --git a/frontend/test/__support__/enterprise-typed.ts b/frontend/test/__support__/enterprise-typed.tsindex 7682bff5165..4a2edde8f9d 100644--- a/frontend/test/__support__/enterprise-typed.ts+++ b/frontend/test/__support__/enterprise-typed.ts@@ -30,6 +30,7 @@ export const ENTERPRISE_PLUGIN_NAME_MAPPING = {shared: "metabase-enterprise/shared",transforms: "metabase-enterprise/transforms","transforms-python": "metabase-enterprise/transforms-python",+ "transforms-testing": "metabase-enterprise/transforms-testing",remote_sync: "metabase-enterprise/remote_sync",public: "metabase-enterprise/public",support: "metabase-enterprise/support",diff --git a/frontend/test/__support__/server-mocks/data-app.ts b/frontend/test/__support__/server-mocks/data-app.tsindex c4c33d23185..0845286c21b 100644--- a/frontend/test/__support__/server-mocks/data-app.ts+++ b/frontend/test/__support__/server-mocks/data-app.ts@@ -1,6 +1,12 @@import fetchMock from "fetch-mock";-import type { DataApp, DataAppRepoStatus } from "metabase-types/api";+import type {+ DataApp,+ DataAppGroup,+ DataAppGroupPermissionWarning,+ DataAppRepoStatus,+ GroupId,+} from "metabase-types/api";export function setupListDataAppsEndpoint(apps: DataApp[]) {fetchMock.get("path:/api/ee/apps", apps);@@ -25,3 +31,34 @@ export function setupUpdateDataAppEndpoint(app: DataApp) {export function setupDeleteDataAppEndpoint(name: string) {fetchMock.delete(`path:/api/ee/apps/${name}`, 204);}++export function setupDataAppGroupsEndpoint(+ name: string,+ groups: DataAppGroup[],+) {+ fetchMock.get(`path:/api/ee/apps/${name}/groups`, groups);+}++export function setupDataAppGroupPermissionWarningsEndpoint(+ name: string,+ warnings: DataAppGroupPermissionWarning[],+) {+ fetchMock.get(+ `path:/api/ee/apps/${name}/group-permission-warnings`,+ warnings,+ );+}++export function setupAddDataAppGroupsEndpoint(+ name: string,+ groups: DataAppGroup[],+) {+ fetchMock.post(`path:/api/ee/apps/${name}/groups`, groups);+}++export function setupRemoveDataAppGroupEndpoint(+ name: string,+ groupId: GroupId,+) {+ fetchMock.delete(`path:/api/ee/apps/${name}/groups/${groupId}`, 204);+}diff --git a/frontend/test/__support__/server-mocks/index.ts b/frontend/test/__support__/server-mocks/index.tsindex 91a3dd590a5..66e11946ca3 100644--- a/frontend/test/__support__/server-mocks/index.ts+++ b/frontend/test/__support__/server-mocks/index.ts@@ -63,6 +63,7 @@ export * from "./task";export * from "./tenant";export * from "./timeline";export * from "./transform";+export * from "./transform-test";export * from "./user";export * from "./user-key-value";export * from "./util";diff --git a/frontend/test/__support__/server-mocks/transform-test.ts b/frontend/test/__support__/server-mocks/transform-test.tsnew file mode 100644index 00000000000..41288fd8d55--- /dev/null+++ b/frontend/test/__support__/server-mocks/transform-test.ts@@ -0,0 +1,30 @@+import fetchMock from "fetch-mock";++import type {+ ListTransformTestRunsResponse,+ RunTransformTestResponse,+ TransformTest,+ TransformTestId,+} from "metabase-types/api";++export function setupListTransformTestsEndpoint(tests: TransformTest[]) {+ fetchMock.get("path:/api/ee/transform-test", tests);+}++export function setupGetTransformTestEndpoint(test: TransformTest) {+ fetchMock.get(`path:/api/ee/transform-test/${test.id}`, test);+}++export function setupListTransformTestRunsEndpoint(+ testId: TransformTestId,+ response: ListTransformTestRunsResponse,+) {+ fetchMock.get(`path:/api/ee/transform-test/${testId}/run`, response);+}++export function setupRunTransformTestEndpoint(+ testId: TransformTestId,+ response: RunTransformTestResponse,+) {+ fetchMock.post(`path:/api/ee/transform-test/${testId}/run`, response);+}diff --git a/resources/migrations/065/20261022_core_session_ended_by_user_index.yaml b/resources/migrations/065/20261022_core_session_ended_by_user_index.yamlnew file mode 100644index 00000000000..52eaf597377--- /dev/null+++ b/resources/migrations/065/20261022_core_session_ended_by_user_index.yaml@@ -0,0 +1,21 @@+## Deleting a user clears core_session.ended_by_user_id through fk_core_session_ended_by_user_id, which scans the table+## without an index. MySQL, MariaDB and H2 index a foreign key's column themselves; Postgres doesn't, and on MySQL a+## second index would take over the constraint and refuse to be dropped on rollback, so this one is Postgres-only.++databaseChangeLog:+ - changeSet:+ id: v65.2026-10-22T01:00:00+ author: ranquild+ comment: Index core_session.ended_by_user_id (PostgreSQL)+ dbms: postgresql+ changes:+ - createIndex:+ tableName: core_session+ indexName: idx_core_session_ended_by_user_id+ columns:+ - column:+ name: ended_by_user_id+ rollback:+ - dropIndex:+ tableName: core_session+ indexName: idx_core_session_ended_by_user_iddiff --git a/resources/migrations/065/20261022_data_app_unique_resource_collection.yaml b/resources/migrations/065/20261022_data_app_unique_resource_collection.yamlnew file mode 100644index 00000000000..0045131dde1--- /dev/null+++ b/resources/migrations/065/20261022_data_app_unique_resource_collection.yaml@@ -0,0 +1,54 @@+## Two data apps can't share one resource collection. A plain index on the column comes first, on every database: on+## MySQL and MariaDB a unique index would otherwise take the place of the index behind the foreign key, and a rollback+## could not drop it. Postgres has that index already (20261006_data_app_resource_collection). Apps that share a+## collection keep it for the first app only; the others are left without one, which an app may be given again.++databaseChangeLog:+ - changeSet:+ id: v65.2026-10-22T00:00:00+ author: ranquild+ comment: Index data apps by their resource collection, where no index exists yet+ preConditions:+ - onFail: MARK_RAN+ - not:+ - indexExists:+ tableName: data_app+ indexName: idx_data_app_resource_collection_id+ changes:+ - createIndex:+ tableName: data_app+ indexName: idx_data_app_resource_collection_id+ columns:+ - column:+ name: resource_collection_id+ rollback: []++ - changeSet:+ id: v65.2026-10-22T00:00:01+ author: ranquild+ comment: Leave a resource collection that data apps share to the first of them only+ changes:+ # the derived table lets MySQL read the table it updates+ - sql:+ sql: >-+ UPDATE data_app SET resource_collection_id = NULL+ WHERE id IN (SELECT id FROM (SELECT later.id+ FROM data_app later+ JOIN data_app earlier+ ON earlier.resource_collection_id = later.resource_collection_id+ AND earlier.id < later.id) shared)+ rollback: []++ - changeSet:+ id: v65.2026-10-22T00:00:02+ author: ranquild+ comment: Add a unique constraint on data_app.resource_collection_id+ changes:+ - addUniqueConstraint:+ tableName: data_app+ columnNames: resource_collection_id+ constraintName: uq_data_app_resource_collection_id+ rollback:+ - dropUniqueConstraint:+ tableName: data_app+ constraintName: uq_data_app_resource_collection_iddiff --git a/rspack.main.config.js b/rspack.main.config.jsindex 627b0864e8d..d00edbf6fd1 100644--- a/rspack.main.config.js+++ b/rspack.main.config.js@@ -192,9 +192,9 @@ const config = {styles: "./css/index.module.css",...(isEEBuild && {"app-data-app":- ENTERPRISE_SRC_PATH + "/data_apps/runtime/app-data-app.tsx",+ ENTERPRISE_SRC_PATH + "/data-apps/runtime/app-data-app.tsx","data-app-vendors":- ENTERPRISE_SRC_PATH + "/data_apps/runtime/iframe-vendors.ts",+ ENTERPRISE_SRC_PATH + "/data-apps/runtime/iframe-vendors.ts",}),},diff --git a/src/metabase/actions/db.clj b/src/metabase/actions/db.cljindex 2eaeaf7230f..7c9424d9ae3 100644--- a/src/metabase/actions/db.clj+++ b/src/metabase/actions/db.clj@@ -88,6 +88,11 @@[collection-id :- ::lib.schema.id/collection](t2/exists? :model/Collection :id collection-id :archived false))+(mu/defn action-collection-id+ "The Collection id of the Action with `action-id`, or nil."+ [action-id :- ::lib.schema.id/action]+ (t2/select-one-fn :collection_id [:model/Action :collection_id] :id action-id))+(mu/defn action-model-id"The model Card id of the Action with `action-id`, or nil."[action-id :- ::lib.schema.id/action]diff --git a/src/metabase/actions/models.clj b/src/metabase/actions/models.cljindex afbf32b29d2..fd690682d84 100644--- a/src/metabase/actions/models.clj+++ b/src/metabase/actions/models.clj@@ -146,13 +146,56 @@[{model-id :model_id, :as action}](assoc action :collection_id (actions.db/card-collection-id model-id)))+(defn- query-card-ids+ "The IDs of the Cards the native `query` reads through card template tags."+ [query]+ (into #{}+ (keep (fn [path]+ (let [{:keys [model id]} (last path)]+ (when (= "Card" model) id))))+ (serdes/mbql-deps true query)))++(defn- data-app-action-error+ "A 400 error for an action in a data app's collection, with `message`."+ [message]+ (ex-info message {:status-code 400}))++(defn- check-data-app-action-query+ "Throws when `query`, of an action in the Collection with `collection-id`, reads a card outside that collection+ while the collection is a data app's."+ [collection-id query]+ (when (and (some? collection-id)+ (perms/data-app-collection? collection-id))+ (let [card-ids (query-card-ids query)+ outside (when (seq card-ids)+ (actions.db/card-ids-outside-collection card-ids collection-id))]+ (when (seq outside)+ (throw (data-app-action-error+ (tru "An action in a data app''s collection can read only the app''s own cards, not card {0}."+ (str/join ", " (sort outside)))))))))++(defn- check-data-app-action+ "Throws unless `action`, when it is in a data app's collection, is a query action of no model that is neither+ archived nor public and whose parameters take no values from a card."+ [{collection-id :collection_id, :as action}]+ (when (and (some? collection-id) (perms/data-app-collection? collection-id))+ (when (or (not= :query (keyword (:type action))) (:model_id action))+ (throw (data-app-action-error (tru "An action in a data app''s collection must be a query action of no model."))))+ (when (:archived action)+ (throw (data-app-action-error (tru "An action in a data app''s collection can''t be archived."))))+ (when (:public_uuid action)+ (throw (data-app-action-error (tru "An action in a data app''s collection can''t be made public."))))+ (when (some #(= "card" (some-> (:values_source_type %) name)) (:parameters action))+ (throw (data-app-action-error (tru "An action in a data app''s collection can''t take a parameter''s values from a card."))))))+(t2/define-before-insert :model/Action[{model-id :model_id, :as action}](u/prog1 (cond-> (public-sharing/add-public-uuid-prefix action)model-id set-model-collection)(when (implicit? action)(check-implicit-action-model model-id))- (check-collection-content <>)))+ (check-collection-content <>)+ (check-data-app-action <>)))(t2/define-before-update :model/Action[{model-id :model_id, :as action}]@@ -165,11 +208,10 @@(check-implicit-actions-supported action))(when (some #(contains? (t2/changes <>) %) [:collection_id :model_id])(check-collection-content <>))- (let [in-data-app? (and (some? (:collection_id <>)) (perms/data-app-collection? (:collection_id <>)))]- (when (and in-data-app? (changed? :archived) (:archived <>))- (throw (ex-info (tru "An action in a data app''s collection can''t be archived.") {:status-code 400})))- (when (and in-data-app? (changed? :public_uuid) (:public_uuid <>))- (throw (ex-info (tru "An action in a data app''s collection can''t be made public.") {:status-code 400})))))))+ (when (some #(contains? (t2/changes <>) %) [:collection_id :model_id :type :archived :public_uuid :parameters])+ (check-data-app-action <>))+ (when (contains? (t2/changes <>) :collection_id)+ (check-data-app-action-query (:collection_id <>) (:dataset_query (actions.db/query-action (:id <>))))))))(defn- set-query-database"`query-action` with the `:database_id` of its query, when it has one."@@ -180,11 +222,21 @@(t2/define-before-insert :model/QueryAction[query-action]- (set-query-database query-action))+ (u/prog1 (set-query-database query-action)+ (check-data-app-action-query (actions.db/action-collection-id (:action_id <>)) (:dataset_query <>))))(t2/define-before-update :model/QueryAction[query-action]- (set-query-database query-action))+ (u/prog1 (set-query-database query-action)+ (when (contains? (t2/changes query-action) :dataset_query)+ (check-data-app-action-query (actions.db/action-collection-id (:action_id <>)) (:dataset_query <>)))))++(t2/define-before-insert :model/ImplicitAction+ [implicit-action]+ (u/prog1 implicit-action+ (when-let [collection-id (actions.db/action-collection-id (:action_id implicit-action))]+ (when (perms/data-app-collection? collection-id)+ (throw (data-app-action-error (tru "An action in a data app''s collection is a query action, so it can''t have an implicit action.")))))))(defn- action-database-ids"The ids of the Databases `action` runs against: its query's, or its model's for an implicit action."@@ -260,33 +312,9 @@;;; ------------------------------------------------ CRUD fns ------------------------------------------------------(defn- query-card-ids- "The IDs of the Cards the native `query` reads through card template tags."- [query]- (into #{}- (keep (fn [path]- (let [{:keys [model id]} (last path)]- (when (= "Card" model) id))))- (serdes/mbql-deps true query)))--(defn- check-data-app-action-query- "Throws when `query`, of an action in the Collection with `collection-id`, reads a card outside that collection- while the collection is a data app's."- [collection-id query]- (when (and (some? collection-id)- (perms/data-app-collection? collection-id))- (let [card-ids (query-card-ids query)- outside (when (seq card-ids)- (actions.db/card-ids-outside-collection card-ids collection-id))]- (when (seq outside)- (throw (ex-info (tru "An action in a data app''s collection can read only the app''s own cards, not card {0}."- (str/join ", " (sort outside)))- {:status-code 400}))))))-;;; TODO (Cam 10/2/25) -- this should just be the default Toucan 2 insert behavior for an action(mu/defn- insert*! :- ::actions.schema/id[action-data :- ::actions.schema/action.for-insert]- (check-data-app-action-query (:collection_id action-data) (:dataset_query action-data))(t2/with-transaction [_conn](let [action (actions.db/insert-action! (select-keys action-data action-columns))row (-> (apply dissoc action-data action-columns)@@ -307,21 +335,8 @@existing-action :- ::actions.schema/action](let [updates (cond-> (assoc updates :type (or (:type updates) (:type existing-action)))(get updates :model_id (:model_id existing-action)) (dissoc :collection_id))]- (check-data-app-action-query (if (contains? updates :collection_id)- (:collection_id updates)- (:collection_id existing-action))- (if (contains? updates :dataset_query)- (:dataset_query updates)- (:dataset_query existing-action)))(t2/with-transaction [_conn]- (when-let [action-row (not-empty (select-keys updates action-columns))]- (actions.db/update-action! id action-row))- (when (and (:archived updates) (not (:archived existing-action)))- (actions.db/delete-dashcards-for-action! id))- (when-let [collection-id (and (contains? updates :collection_id)- (not= (:collection_id updates) (:collection_id existing-action))- (:collection_id updates))]- (api/check-400 (actions.db/unarchived-collection-exists? collection-id)))+ ;; the query row first: a move into a data app's collection checks the query the action then holds(when-let [type-row (not-empty (cond-> (apply dissoc updates :id action-columns)(= (or (:type updates) (:type existing-action)):implicit)@@ -338,6 +353,14 @@(case (:type existing-action):query (actions.db/update-query-action! id type-row):implicit (actions.db/update-implicit-action! id type-row)))))+ (when-let [action-row (not-empty (select-keys updates action-columns))]+ (actions.db/update-action! id action-row))+ (when (and (:archived updates) (not (:archived existing-action)))+ (actions.db/delete-dashcards-for-action! id))+ (when-let [collection-id (and (contains? updates :collection_id)+ (not= (:collection_id updates) (:collection_id existing-action))+ (:collection_id updates))]+ (api/check-400 (actions.db/unarchived-collection-exists? collection-id)))(collection/check-for-remote-sync-update (t2/instance :model/Action existing-action)))))(mu/defn update!diff --git a/src/metabase/collections/children.clj b/src/metabase/collections/children.cljindex 59e73ce513c..c1e1c54c479 100644--- a/src/metabase/collections/children.clj+++ b/src/metabase/collections/children.clj@@ -497,14 +497,14 @@[:= :action.archived (boolean archived?)]]})(defmethod post-process-collection-children :action- [_ _options _collection rows]+ [_ _options collection rows](for [row rows](-> (dissoc row:collection_position :display :authority_level :moderated_status :icon :personal_owner_id:collection_preview :dataset_query :table_id :query_type :is_upload :namespace)(update :archived api/bit->boolean)(update :archived_directly api/bit->boolean)- (assoc :collection_namespace "data-actions"))))+ (assoc :collection_namespace (some-> (:namespace collection) name)))))(defmethod post-process-collection-children :timeline[_ _options _collection rows]@@ -1155,7 +1155,7 @@(for [model-kw (cond-> [:collection :dataset :metric :card :dashboard :pulse :snippet :timeline :document :exploration :transform];; Tables in collections are an EE feature (library)(premium-features/has-feature? :library) (conj :table)- (= "data-actions" (some-> collection-namespace name)) (conj :action))+ (contains? #{"data-actions" "data-apps"} (some-> collection-namespace name)) (conj :action)):let [toucan-model (model-name->toucan-model model-kw)allowed-namespaces (collection/allowed-namespaces toucan-model)]:when (or (= model-kw :collection)@@ -1166,18 +1166,11 @@"Fetch a sequence of 'child' objects belonging to a Collection, filtered using `options`."[{collection-namespace :namespace, :as collection} :- collection/CollectionWithLocationAndIDOrRoot{:keys [models created-by-id], :as options} :- CollectionChildrenOptions]- (let [valid-models (for [model-kw (cond-> [:collection :dataset :metric :card :dashboard :pulse :snippet :timeline :document :exploration :transform]- ;; Tables in collections are an EE feature (library)- (premium-features/has-feature? :library) (conj :table)- (= "data-actions" (some-> collection-namespace name)) (conj :action))+ (let [valid-models (for [model-kw (valid-collection-models collection-namespace);; only fetch models that are specified by the `model` param; or everything if it's empty:when (or (empty? models) (contains? models model-kw));; a creator filter drops models that don't index a creator- :when (or (nil? created-by-id) (contains? creator-filterable-models model-kw))- :let [toucan-model (model-name->toucan-model model-kw)- allowed-namespaces (collection/allowed-namespaces toucan-model)]- :when (or (= model-kw :collection)- (contains? allowed-namespaces (keyword collection-namespace)))]+ :when (or (nil? created-by-id) (contains? creator-filterable-models model-kw))]model-kw)](if (seq valid-models)(collection-children* collection valid-models (assoc options :collection-namespace collection-namespace))diff --git a/src/metabase/collections/models/collection.clj b/src/metabase/collections/models/collection.cljindex 90051525cf6..bb2314ca001 100644--- a/src/metabase/collections/models/collection.clj+++ b/src/metabase/collections/models/collection.clj@@ -2107,9 +2107,12 @@(not (is-trash? collection-before-updates))[400 "You cannot modify the Trash Collection."])(api/check- (not (and (or (:archived collection-updates) (some? (:authority_level collection-updates)))+ (not (and (or (:archived collection-updates)+ (some? (:authority_level collection-updates))+ (contains? collection-updates :location)+ (some collection-updates [:type :personal_owner_id :is_sample :archive_operation_id]))(perms/data-app-collection? (:id collection-before-updates))))- [400 "You cannot move a data app's collection to the trash or make it official."])+ [400 "A data app's collection stays a top-level collection of data apps: it can't be moved, trashed, made official or given a type."]);; VARIOUS CHECKS BEFORE DOING ANYTHING:;; (1) if this is a personal Collection, check that the 'propsed' changes are allowed(when (or (:personal_owner_id collection-before-updates)diff --git a/src/metabase/lib/core.cljc b/src/metabase/lib/core.cljcindex e3a5ed1a078..ce073b6f4b6 100644--- a/src/metabase/lib/core.cljc+++ b/src/metabase/lib/core.cljc@@ -1744,6 +1744,7 @@all-implicitly-joined-field-idsall-implicitly-joined-table-idsall-measure-ids+ all-metric-idsall-segment-idsall-source-card-idsall-source-card-ids-recursivediff --git a/src/metabase/lib/walk/util.cljc b/src/metabase/lib/walk/util.cljcindex bdd46af842b..d6230d661ff 100644--- a/src/metabase/lib/walk/util.cljc+++ b/src/metabase/lib/walk/util.cljc@@ -73,7 +73,9 @@(assoc template-tag :lib.walk/template-tag-name template-tag-name)))(all-template-tags-map query))))-(defn- all-metric-ids [query]+(mu/defn all-metric-ids :- [:maybe [:set {:min 1} ::lib.schema.id/metric]]+ "Return a set of all metric IDs referenced by `:metric` clauses anywhere in the query."+ [query :- ::lib.schema/query](let [metric-ids (volatile! (transient #{}))](lib.walk/walk-clausesquerydiff --git a/src/metabase/queries/db.clj b/src/metabase/queries/db.cljindex bc581e8891e..bd2c65a7f2a 100644--- a/src/metabase/queries/db.clj+++ b/src/metabase/queries/db.clj@@ -4,6 +4,7 @@methods."(:require[metabase.app-db.core :as mdb]+ [metabase.collections.core :as collections][metabase.dashboards.schema :as dashboards.schema][metabase.lib-be.schema :as lib-be.schema][metabase.lib.schema.id :as lib.schema.id]@@ -590,6 +591,23 @@:from [:stored_result_use]:where [:= :card_id card-id]}]))+(mu/defn unpublished-table-names :- [:set :string]+ "Among the Tables with `table-ids`, the names of those not published to the Library."+ [table-ids :- [:set {:min 1} ::lib.schema.id/table]]+ (or (t2/select-fn-set :name [:model/Table :name] :id [:in table-ids] :is_published false+ {:from [(warehouse-schema-overlay/table-query)]})+ #{}))++(mu/defn library-metric-ids :- [:set ::lib.schema.id/card]+ "Among `card-ids`, the IDs of the metrics in the Library's Metrics collection or one of its subcollections."+ [card-ids :- [:set {:min 1} ::lib.schema.id/card]]+ (or (t2/select-fn-set :id [:model/Card :report_card.id] {:join [:collection [:= :collection.id :report_card.collection_id]]+ :where [:and+ [:in :report_card.id card-ids]+ [:= :report_card.type "metric"]+ [:= :collection.type collections/library-metrics-collection-type]]})+ #{}))+(defn card-ids-outside-collection"Among `card-ids`, the IDs of the cards that are not in the collection with `collection-id`."[card-ids collection-id]diff --git a/src/metabase/queries/models/card.clj b/src/metabase/queries/models/card.cljindex 52cf8f28a76..d29be54592d 100644--- a/src/metabase/queries/models/card.clj+++ b/src/metabase/queries/models/card.clj@@ -22,6 +22,7 @@[metabase.lib-be.core :as lib-be][metabase.lib-be.schema :as lib-be.schema][metabase.lib.core :as lib]+ [metabase.lib.metadata :as lib.metadata][metabase.lib.schema :as lib.schema][metabase.lib.schema.id :as lib.schema.id][metabase.lib.schema.metadata :as lib.schema.metadata]@@ -995,32 +996,105 @@:dashboard-question(:type card)))+(defn- data-app-card-error+ "A 400 error for a card in a data app's collection, with `message`."+ [message]+ (ex-info message {:status-code 400}))++(defn- card-labels+ "The cards with `card-ids` as they appear in an error, by name and ID."+ [metadata-providerable card-ids]+ (str/join ", " (for [{card-name :name, card-id :id} (sort-by :id (lib.metadata/bulk-metadata metadata-providerable :metadata/card card-ids))]+ (format "\"%s\" (%d)" card-name card-id))))++(defn- tables-read+ "The IDs of the tables `query` reads: its source tables, explicit joins included, and the tables it reaches through a+ foreign key."+ [query]+ (set/union (set (lib/all-source-table-ids query))+ (set (lib/all-implicitly-joined-table-ids query))))++(defn- macro-tables-read+ "The IDs of the tables that the definitions of the segments and measures `query` uses read."+ [query]+ (into #{}+ (comp (keep :definition)+ (filter (comp seq :stages))+ (mapcat #(tables-read (lib/query query %))))+ (concat (some->> (lib/all-segment-ids query) (lib.metadata/bulk-metadata query :metadata/segment))+ (some->> (lib/all-measure-ids query) (lib.metadata/bulk-metadata query :metadata/measure)))))++(defn- remapped-tables-read+ "The IDs of the tables whose columns replace a column `query` returns, through a foreign key remapping."+ [query]+ (into #{}+ (keep :table-id)+ (some->> (lib/returned-columns query)+ (keep (comp :field-id :lib/external-remap))+ not-empty+ (lib.metadata/bulk-metadata query :metadata/column))))++(defn- check-data-app-card-query+ "Returns the IDs of the Library metrics `dataset_query` aggregates, and throws unless it is an MBQL query on a+ database, based on no card, that reads only tables published to the Library, through its segments, measures and+ remapped columns too; a load skips the published check, since it may load a table's published state later."+ [{:keys [dataset_query]}]+ (when-not (:database dataset_query)+ (throw (data-app-card-error (tru "A card in a data app''s collection must hold a query on a database."))))+ (let [query (lib/query (lib-be/application-database-metadata-provider (:database dataset_query)) dataset_query)+ metric-ids (set (lib/all-metric-ids query))+ card-ids (set/difference (set (lib/all-source-card-ids query)) metric-ids)]+ (when (lib/any-native-stage? query)+ (throw (data-app-card-error (tru "A card in a data app''s collection must be built with the query builder, not SQL."))))+ (when (seq card-ids)+ (throw (data-app-card-error (tru "A card in a data app''s collection can read only tables published to the Library, not the card {0}."+ (card-labels query card-ids)))))+ (when-let [outside (seq (when (seq metric-ids)+ (set/difference metric-ids (queries.db/library-metric-ids metric-ids))))]+ (throw (data-app-card-error (tru "A card in a data app''s collection can use only metrics from the Library, not the metric {0}."+ (card-labels query outside)))))+ (when-not mi/*deserializing?*+ (when-let [unpublished (seq (some-> (not-empty (set/union (tables-read query)+ (macro-tables-read query)+ (remapped-tables-read query)))+ queries.db/unpublished-table-names))]+ (throw (data-app-card-error (tru "A card in a data app''s collection can read only tables published to the Library, not {0}. Publish them, or read other tables."+ (str/join ", " (sort unpublished)))))))+ metric-ids))+(defn- check-data-app-card- "Throws unless `card`, when it is in a data app's collection, is a question or metric that is not archived, public- or embedded, reading no card outside the collection, which is what a remote-sync pull of the app accepts."+ "Throws unless `card`, when it is in a data app's collection, is a question or metric in no dashboard or document, not+ archived, public or embedded, whose query reads only the Library, and whose other references, such as parameter+ values, name only cards in the collection."[{:keys [collection_id] :as card}](when (and (some? collection_id)(perms/data-app-collection? collection_id));; a new card without a type is a question, the column's default(when (or (not (contains? #{:question :metric} (keyword (or (:type card) :question))))+ (:dashboard_id card)+ (:document_id card)(:archived card)(:public_uuid card)(:enable_embedding card)(:embedding_params card)(:embedding_type card))- (throw (ex-info "A card in a data app's collection must be a question or metric that is not archived, public or embedded"- {:status-code 400})))- (let [card-ids (into #{}- (keep (fn [path]- (let [{:keys [model id]} (last path)]- (when (= "Card" model) id))))- (serdes/serialization-dependencies "Card" card))- outside (when (seq card-ids)- (queries.db/card-ids-outside-collection card-ids collection_id))]+ (throw (data-app-card-error (tru "A card in a data app''s collection must be a question or metric, in no dashboard or document, that is not archived, public or embedded."))))+ (let [metric-ids (check-data-app-card-query card)+ card-ids (into #{}+ (keep (fn [path]+ (let [{:keys [model id]} (last path)]+ (when (and (= "Card" model) (not (metric-ids id))) id))))+ (serdes/serialization-dependencies "Card" card))+ outside (when (seq card-ids)+ (queries.db/card-ids-outside-collection card-ids collection_id))](when (seq outside)- (throw (ex-info (str "A card in a data app's collection can read only the app's own cards, not card "- (str/join ", " (sort outside)))- {:status-code 400}))))))+ (throw (data-app-card-error (tru "A card in a data app''s collection can reference only the app''s own cards and Library metrics, not card {0}."+ (str/join ", " (sort outside)))))))))++(def ^:private data-app-card-columns+ "The columns [[check-data-app-card]] reads; an update that changes none of them leaves a card as it was checked."+ #{:collection_id :dashboard_id :document_id :type :archived :public_uuid :enable_embedding :embedding_params+ :embedding_type :dataset_query :parameters :parameter_mappings :visualization_settings})(t2/define-before-insert :model/Card[card]@@ -1121,7 +1195,7 @@;; Only allow it to nil out a stale table_id when the query itself is changing.(populate-query-fields (contains? changes :dataset_query));; after the query's columns are set again: `source_card_id` is one of the references it reads- (doto check-data-app-card)+ (cond-> (some data-app-card-columns (keys changes)) (doto check-data-app-card))(clear-metabot-origin changes)(pre-update changes)(move-model-actions original)diff --git a/test/metabase/app_db/schema_migrations_test.clj b/test/metabase/app_db/schema_migrations_test.cljindex bde7bf8b067..9d2cce799bd 100644--- a/test/metabase/app_db/schema_migrations_test.clj+++ b/test/metabase/app_db/schema_migrations_test.clj@@ -4031,3 +4031,33 @@(migrate!)(is (true? (t2/select-one-fn :is_default :python_library :id unedited)))(is (false? (t2/select-one-fn :is_default :python_library :id edited)))))))++(deftest data-app-unique-resource-collection-test+ (testing "v65.2026-10-22T00:00:00-02: a shared resource collection stays with the first app, and no two apps share one"+ (impl/test-migrations ["v65.2026-10-22T00:00:00" "v65.2026-10-22T00:00:02"] [migrate!]+ (let [collection! (fn [slug]+ (t2/insert-returning-pk! :collection {:name slug+ :slug slug+ :location "/"+ :namespace "data-apps"+ :entity_id (u/generate-nano-id)+ :created_at :%now}))+ app! (fn [slug collection-id]+ (t2/insert-returning-pk! :data_app {:name slug+ :display_name slug+ :bundle_path "dist/index.js"+ :entity_id (u/generate-nano-id)+ :resource_collection_id collection-id+ :created_at :%now+ :updated_at :%now}))+ shared (collection! "shared")+ own (collection! "own")+ first-app (app! "first" shared)+ second-app (app! "second" shared)+ other-app (app! "other" own)]+ (migrate!)+ (is (= shared (t2/select-one-fn :resource_collection_id :data_app :id first-app)))+ (is (nil? (t2/select-one-fn :resource_collection_id :data_app :id second-app)))+ (is (= own (t2/select-one-fn :resource_collection_id :data_app :id other-app)))+ (testing "a second app on a collection is refused"+ (is (thrown? Exception (app! "third" shared))))))))diff --git a/test/metabase/collections_rest/api_test.clj b/test/metabase/collections_rest/api_test.cljindex b87571e37af..d2919121520 100644--- a/test/metabase/collections_rest/api_test.clj+++ b/test/metabase/collections_rest/api_test.clj@@ -10,6 +10,7 @@[metabase.collections.models.collection :as collection][metabase.collections.models.collection-test :as collection-test][metabase.collections.test-utils :refer [personal-collection with-library-not-synced without-library]]+ [metabase.models.interface :as mi][metabase.notification.api.notification-test :as api.notification-test][metabase.notification.test-util :as notification.tu][metabase.permissions.core :as perms]@@ -1918,6 +1919,33 @@(is (= #{}(actions (str "collection/" regular-id "/items"))))))))+(deftest data-app-collection-items-test+ (testing "GET /api/collection/:id/items lists the actions and questions of a data app collection"+ (mt/with-temp [:model/Collection {app-coll-id :id} {:namespace "data-apps", :name "Data app collection"}+ :model/Collection {actions-coll-id :id} {:namespace "data-actions", :name "Data actions folder"}+ :model/Action {in-app :id} {:type :query, :name "In app", :collection_id app-coll-id}+ :model/QueryAction _ {:action_id in-app+ :database_id (mt/id)+ :dataset_query (mt/native-query {:query "DELETE FROM venues"})}+ :model/Action {in-folder :id} {:type :query, :name "In folder", :collection_id actions-coll-id}+ :model/QueryAction _ {:action_id in-folder+ :database_id (mt/id)+ :dataset_query (mt/native-query {:query "DELETE FROM venues"})}]+ (binding [mi/*deserializing?* true]+ (mt/with-temp [:model/Card _ {:name "App question"+ :collection_id app-coll-id+ :dataset_query (mt/mbql-query venues)}]+ (let [items (fn [coll-id model]+ (->> (mt/user-http-request :crowberto :get 200 (str "collection/" coll-id "/items") :models model)+ :data+ (map #(select-keys % [:name :model :collection_namespace]))))]+ (is (= [{:name "In app", :model "action", :collection_namespace "data-apps"}]+ (items app-coll-id "action")))+ (is (= [{:name "App question", :model "card"}]+ (map #(dissoc % :collection_namespace) (items app-coll-id "card"))))+ (is (= [{:name "In folder", :model "action", :collection_namespace "data-actions"}]+ (items actions-coll-id "action")))))))))+(deftest snippet-collection-items-count-only-test(testing "The snippets namespace is unpaginated, but a count-only request still keeps its LIMIT"(mt/with-temp [:model/NativeQuerySnippet _ {:name "UXW5016 root snippet"}]diff --git a/test/metabase/queries/models/card_test.clj b/test/metabase/queries/models/card_test.cljindex 807a4f7b26a..de6b097643c 100644--- a/test/metabase/queries/models/card_test.clj+++ b/test/metabase/queries/models/card_test.clj@@ -1182,16 +1182,19 @@(deftest card-in-a-data-apps-collection-is-admin-only-test(testing "Only administrators write a card in a collection of the data apps namespace"- (mt/with-temp [:model/Collection {collection-id :id} {:namespace "data-apps"}- :model/Card card {:collection_id collection-id}]- (mt/with-test-user :crowberto- (is (true? (mi/can-write? card)))- (is (true? (mi/can-write? :model/Card (:id card))))- (is (true? (:can_write (t2/hydrate card :can_write))))- (is (true? (mi/can-create? :model/Card {:collection_id collection-id}))))- (mt/with-test-user :rasta- (is (false? (mi/can-write? card)))- (is (false? (mi/can-create? :model/Card {:collection_id collection-id})))))))+ ;; created as a load creates it, which doesn't check that the table is published+ (binding [mi/*deserializing?* true]+ (mt/with-temp [:model/Collection {collection-id :id} {:namespace "data-apps"}+ :model/Card card {:collection_id collection-id+ :dataset_query (mt/mbql-query venues)}]+ (mt/with-test-user :crowberto+ (is (true? (mi/can-write? card)))+ (is (true? (mi/can-write? :model/Card (:id card))))+ (is (true? (:can_write (t2/hydrate card :can_write))))+ (is (true? (mi/can-create? :model/Card {:collection_id collection-id}))))+ (mt/with-test-user :rasta+ (is (false? (mi/can-write? card)))+ (is (false? (mi/can-create? :model/Card {:collection_id collection-id}))))))))(deftest ^:parallel breakouts->identifier->action-fn-test(are [b1 b2 expected-identifier->action] (=? expected-identifier->action