Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

64.1 KB
Raw Blame
const { H } = cy;
import { USERS, USER_GROUPS, WRITABLE_DB_ID } from "e2e/support/cypress_data";
import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";
import {
  FIRST_COLLECTION_ID,
  NORMAL_PERSONAL_COLLECTION_ID,
  ORDERS_DASHBOARD_ID,
  ORDERS_QUESTION_ID,
  SECOND_COLLECTION_ID,
  THIRD_COLLECTION_ID,
} from "e2e/support/cypress_sample_instance_data";
import { uuid } from "metabase/utils/uuid";
import {
  createMockDashboardCard,
  createMockTextDashboardCard,
} from "metabase-types/api/mocks";

const { ORDERS, ORDERS_ID } = SAMPLE_DATABASE;
const { ALL_USERS_GROUP } = USER_GROUPS;

describe("scenarios > embedding > full app", () => {
  beforeEach(() => {
    H.restore();
    cy.signInAsAdmin();
    H.activateToken("pro-self-hosted");
    cy.intercept("POST", "/api/card/*/query").as("getCardQuery");
    cy.intercept("POST", "/api/dashboard/**/query").as("getDashCardQuery");
    cy.intercept("GET", "/api/dashboard/*").as("getDashboard");
    cy.intercept("GET", "/api/automagic-dashboards/**").as("getXrayDashboard");
  });

  describe("home page navigation", () => {
    it("should show or hide the top and side nav by params", () => {
      cy.log("show the top and side nav by default");
      H.visitFullAppEmbeddingUrl({ url: "/" });
      cy.wait("@getXrayDashboard");

      H.appBar()
        .should("be.visible")
        .within(() => {
          cy.findByTestId("main-logo").should("be.visible");
          cy.button(/New/).should("not.exist");
          cy.findByPlaceholderText("Search…").should("not.exist");
        });

      sideNav().should("be.visible");

      cy.log("hide the top nav when nothing is shown");
      H.visitFullAppEmbeddingUrl({
        url: "/",
        qs: { side_nav: false, logo: false },
      });
      cy.wait("@getXrayDashboard");
      cy.findByTestId("home-page").should("be.visible");
      H.appBar().should("not.exist");

      cy.log("hide the top nav by an explicit param");
      H.visitFullAppEmbeddingUrl({ url: "/", qs: { top_nav: false } });
      cy.wait("@getXrayDashboard");
      cy.findByTestId("home-page").should("be.visible");
      H.appBar().should("not.exist");

      cy.log(
        "keep showing sidebar toggle button when logo, breadcrumbs, the new button, and search are hidden",
      );
      H.visitFullAppEmbeddingUrl({
        url: "/",
        qs: {
          logo: false,
          breadcrumbs: false,
          search: false,
          new_button: false,
        },
      });
      cy.wait("@getXrayDashboard");

      sideNav().should("be.visible");
      H.appBar()
        .should("be.visible")
        .within(() => {
          cy.button("Toggle sidebar").should("be.visible").click();
        });
      sideNav().should("not.be.visible");

      cy.log("hide the side nav by a param");
      H.visitFullAppEmbeddingUrl({ url: "/", qs: { side_nav: false } });
      cy.wait("@getXrayDashboard");
      H.appBar().within(() => {
        cy.findByTestId("main-logo").should("be.visible");
        cy.button("Toggle sidebar").should("not.exist");
      });
      sideNav().should("not.exist");

      cy.log("show question creation controls by a param");
      H.visitFullAppEmbeddingUrl({ url: "/", qs: { new_button: true } });
      cy.wait("@getXrayDashboard");
      H.appBar().within(() => {
        cy.button(/New/).should("be.visible");
      });

      cy.log("preserve params when navigating");
      H.visitFullAppEmbeddingUrl({ url: "/", qs: { search: true } });
      cy.wait("@getXrayDashboard");

      H.appBar().within(() => {
        cy.findByPlaceholderText("Search…").should("be.visible");
      });

      sideNav().findByText("Our analytics").click();

      cy.findAllByRole("rowgroup")
        .should("contain", "Orders in a dashboard")
        .and("be.visible");

      H.appBar().within(() => {
        cy.findByPlaceholderText("Search…").should("be.visible");
      });

      cy.log(
        "disable home link when top nav is enabled but side nav is disabled",
      );
      visitDashboardUrl({
        url: `/dashboard/${ORDERS_DASHBOARD_ID}`,
        qs: { top_nav: true, side_nav: false },
      });
      cy.findByTestId("main-logo-link").should(
        "have.attr",
        "disabled",
        "disabled",
      );

      cy.log("browse data: hide the top nav when nothing is shown");
      H.visitFullAppEmbeddingUrl({
        url: "/browse/databases",
        qs: { side_nav: false, logo: false },
      });
      cy.findByRole("heading", { name: /Databases/ }).should("be.visible");
      sideNav().should("not.exist");
      H.appBar().should("not.exist");
    });
  });

  describe("questions", () => {
    it("should show or hide the question header and top nav by params", () => {
      cy.log("show the question header by default");
      visitQuestionUrl({ url: "/question/" + ORDERS_QUESTION_ID });

      cy.findByTestId("qb-header").should("be.visible");
      cy.findByTestId("qb-header-left-side").realHover();
      cy.button(/Edited/).should("be.visible");

      cy.icon("refresh").should("be.visible");
      cy.findByTestId("notebook-button").should("be.visible");
      cy.findByTestId("qb-header")
        .button(/Summarize/)
        .should("be.visible");
      cy.findByTestId("qb-header")
        .button(/Filter/)
        .should("be.visible");

      cy.log("hide the question header by a param");
      visitQuestionUrl({
        url: "/question/" + ORDERS_QUESTION_ID,
        qs: { header: false },
      });

      H.tableInteractive().should("be.visible");
      cy.findByTestId("qb-header").should("not.exist");

      cy.log("hide the question's additional info by a param");
      visitQuestionUrl({
        url: "/question/" + ORDERS_QUESTION_ID,
        qs: { additional_info: false },
      });
      // the app bar only shows breadcrumbs while the navbar is closed
      H.closeNavigationSidebar();

      cy.findByTestId("app-bar")
        .findByText("Our analytics")
        .should("be.visible");
      cy.findByTestId("qb-header").should("be.visible");
      cy.findByTestId("qb-header")
        .findByText(/Edited/)
        .should("not.exist");

      cy.log(
        "hide the question's action buttons by a param, and send the 'X-Metabase-Client' header for api requests",
      );
      H.visitFullAppEmbeddingUrl({
        url: "/question/" + ORDERS_QUESTION_ID,
        qs: { action_buttons: false },
      });
      cy.wait("@getCardQuery").then(({ request }) => {
        expect(request?.headers?.["x-metabase-client"]).to.equal(
          "embedding-iframe-full-app",
        );
      });

      cy.icon("refresh").should("be.visible");
      cy.findByTestId("notebook-button").should("not.exist");
      cy.button(/Summarize/).should("not.exist");
      cy.button(/Filter/).should("not.exist");

      cy.log("not hide the top nav when the logo is still visible");
      visitQuestionUrl({
        url: "/question/" + ORDERS_QUESTION_ID,
        qs: { breadcrumbs: false },
      });

      H.appBar().within(() => {
        cy.findByTestId("main-logo").should("be.visible");
        cy.findByText("Our analytics").should("not.exist");
      });

      // This can't be unit test in AppBar since the logic to hide the AppBar is in its parent component
      cy.log("desktop: hide main header when there's nothing to display there");
      visitQuestionUrl({
        url: "/question/" + ORDERS_QUESTION_ID,
        qs: { side_nav: false, logo: false, breadcrumbs: false },
      });
      cy.findByDisplayValue("Orders");
      cy.findByTestId("app-bar").should("not.exist");
      cy.findByTestId("main-logo").should("not.exist");
      cy.icon("sidebar_closed").should("not.exist");
      cy.button("Toggle sidebar").should("not.exist");

      cy.log("mobile: hide main header when there's nothing to display there");
      cy.viewport("iphone-x");
      visitQuestionUrl({
        url: "/question/" + ORDERS_QUESTION_ID,
        qs: { side_nav: false, logo: false, breadcrumbs: false },
      });
      cy.findByDisplayValue("Orders");
      cy.findByTestId("app-bar").should("not.exist");
      cy.findByTestId("main-logo").should("not.exist");
      cy.icon("sidebar_closed").should("not.exist");
      cy.button("Toggle sidebar").should("not.exist");
    });

    describe("question creation", () => {
      beforeEach(() => {
        cy.signOut();
        cy.signInAsNormalUser();
      });

      it("should allow to create a new question from the navbar and show the database for a new native question (metabase#21511)", () => {
        // Simple data picker
        H.visitFullAppEmbeddingUrl({
          url: "/collection/root",
          qs: { top_nav: true, new_button: true, side_nav: false },
        });

        cy.button("New").click();
        H.popover().findByText("Question").click();
        H.popover().findByText("Orders").click();

        // Multi-stage data picker
        H.visitFullAppEmbeddingUrl({
          url: "/collection/root",
          qs: {
            top_nav: true,
            new_button: true,
            side_nav: false,
            data_picker: "staged",
          },
        });

        cy.button("New").click();
        H.popover().findByText("Question").click();
        H.popover().within(() => {
          cy.findByText("Raw Data").click();
          cy.findByText("Orders").click();
        });

        cy.log("show the database for a new native question");
        const newQuestionQuery = {
          dataset_query: {
            database: null,
            native: {
              query: "",
            },
            type: "native",
          },
          visualization_settings: {},
        };

        H.visitFullAppEmbeddingUrl({
          url: `/question#${H.adhocQuestionHash(newQuestionQuery)}`,
          qs: { side_nav: false },
        });

        cy.findByTestId("native-query-editor-container")
          .findByText(/Sample Database/)
          .should("be.visible");
      });
    });
  });

  describe("notebook simple data picker", () => {
    const ordersCardDetails = {
      name: "Card",
      type: "question",
      query: {
        "source-table": ORDERS_ID,
      },
    };

    /**
     * @param {object} option
     * @param {import("metabase/redux/store").InteractiveEmbeddingOptions} [option.searchParameters]
     */
    function startNewEmbeddingQuestion({ searchParameters } = {}) {
      H.visitFullAppEmbeddingUrl({
        url: "/",
        qs: { new_button: true, ...searchParameters },
      });
      cy.button("New").click();
      H.popover().findByText("Question").click();
    }

    function clickOnDataSource(sourceName) {
      H.getNotebookStep("data").findByText(sourceName).click();
    }

    /**
     *
     * @param {object} options
     * @param {string} options.tableName
     * @param {string} [options.schemaName]
     * @param {string} [options.databaseName]
     */
    function verifyTableSelected({ tableName, schemaName, databaseName }) {
      cy.wait("@getTableMetadata").then(({ response }) => {
        cy.wrap(response.body).its("display_name").should("equal", tableName);
        if (schemaName) {
          cy.wrap(response.body).its("schema").should("equal", schemaName);
        }
        if (databaseName) {
          cy.wrap(response.body).its("db.name").should("equal", databaseName);
        }
      });
    }

    function verifyCardSelected({ alias, cardName, collectionName }) {
      cy.wait(alias).then(({ response }) => {
        cy.wrap(response.body).its("name").should("equal", cardName);
        cy.wrap(response.body)
          .its("collection.name")
          .should("equal", collectionName);
      });
    }

    beforeEach(() => {
      cy.signInAsNormalUser();
      cy.intercept("GET", "/api/table/*/query_metadata").as("getTableMetadata");
    });

    it('should respect "entity_types" search parameter (EMB-272)', () => {
      cy.log("test default `entity_types`");
      startNewEmbeddingQuestion();
      H.popover().within(() => {
        cy.findByRole("link", { name: "Reviews" }).should("be.visible");
        cy.findByRole("link", { name: "Orders Model" }).should("be.visible");
      });

      cy.log('test `entity_types=["table"]`');
      startNewEmbeddingQuestion({
        searchParameters: { entity_types: "table" },
      });
      H.popover().within(() => {
        cy.findByRole("link", { name: "Reviews" }).should("be.visible");
        cy.findByRole("link", { name: "Orders Model" }).should("not.exist");
      });

      cy.log('test `entity_types=["model"]`');
      startNewEmbeddingQuestion({
        searchParameters: { entity_types: "model" },
      });
      H.popover().within(() => {
        cy.findByRole("link", { name: "Reviews" }).should("not.exist");
        cy.findByRole("link", { name: "Orders Model" }).should("be.visible");
      });

      cy.log(
        'test `entity_types=["question"]`, question should be ignored, and use the default value ["model", "table"] (metabase#58357)',
      );
      H.createQuestion(ordersCardDetails);
      startNewEmbeddingQuestion({
        searchParameters: {
          entity_types: "question",
        },
      });
      H.popover().within(() => {
        cy.findByRole("link", { name: "Reviews" }).should("be.visible");
        cy.findByRole("link", { name: "Orders Model" }).should("be.visible");
        // Questions shouldn't be shown
        cy.findByRole("link", { name: "Card" }).should("not.exist");
      });
    });

    describe("table", () => {
      it(
        "should select a table when there are multiple databases",
        { tags: "@external" },
        () => {
          H.restore("postgres-12");
          cy.signInAsAdmin();
          startNewEmbeddingQuestion();
          selectFirstDataSource("Orders");

          cy.log(
            "assert that even after selecting a data source from one database, the data picker still shows the other data sources database",
          );
          cy.findByTestId("data-step-cell").click();
          H.popover().findAllByRole("link").should("have.length", 13);

          cy.log("close the data picker popover");
          cy.findByTestId("data-step-cell").click();

          cy.log(
            "assert that the data sources should be filtered by the selected database from the starting data source.",
          );
          H.getNotebookStep("data").button("Join data").click();
          H.popover().findAllByRole("link").should("have.length", 8);
          selectDataSource("Accounts");

          verifyTableSelected({
            tableName: "Orders",
            databaseName: "QA Postgres12",
          });
          verifyTableSelected({
            tableName: "Accounts",
            databaseName: "QA Postgres12",
          });
        },
      );

      it("should be able to join a table when the data source is a table", () => {
        startNewEmbeddingQuestion();
        selectDataSource("Orders");
        clickOnDataSource("Orders");
        H.popover().findByRole("link", { name: "Products" }).should("exist");
        cy.findByTestId("data-step-cell").click();
        H.getNotebookStep("data").button("Join data").click();
        H.popover().findByText("Products").click();
        verifyTableSelected({
          tableName: "Orders",
          databaseName: "Sample Database",
        });
        verifyTableSelected({
          tableName: "Products",
          databaseName: "Sample Database",
        });
      });
    });

    describe("card", () => {
      it("should only offer models as data sources in every collection the user can see", () => {
        createCollectionMatrixCards({ withQuestions: true }).then(
          (modelIds) => {
            COLLECTION_CASES.forEach((testCase, index) => {
              const modelName = getMatrixModelName(testCase.location);
              const questionName = getMatrixQuestionName(testCase.location);
              cy.log(`${testCase.user} user, model in ${testCase.location}`);

              signInForCollectionCase(testCase);
              cy.intercept({
                method: "GET",
                pathname: `/api/card/${modelIds[testCase.location]}`,
              }).as(`getMatrixModel${index}`);

              startNewEmbeddingQuestion();
              H.popover()
                .findByRole("link", { name: modelName })
                .should("exist");
              H.popover().should("not.contain", questionName);

              selectDataSource(modelName);
              verifyCardSelected({
                alias: `@getMatrixModel${index}`,
                cardName: modelName,
                collectionName: testCase.collectionName,
              });
            });
          },
        );
      });

      it("should only offer models when joining a card to a table", () => {
        const questionDetails = {
          ...ordersCardDetails,
          name: "Joined question",
          type: "question",
          collection_id: FIRST_COLLECTION_ID,
        };
        const modelDetails = {
          ...ordersCardDetails,
          name: "Joined model",
          type: "model",
          collection_id: FIRST_COLLECTION_ID,
        };
        H.createQuestion(questionDetails);
        H.createQuestion(modelDetails);
        startNewEmbeddingQuestion();
        selectDataSource("Products");
        H.getNotebookStep("data").button("Join data").click();
        H.popover()
          .findByRole("link", { name: modelDetails.name })
          .should("exist");
        H.popover().should("not.contain", questionDetails.name);
        selectDataSource(modelDetails.name);
        verifyTableSelected({
          tableName: "Products",
          databaseName: "Sample Database",
        });
        verifyTableSelected({
          tableName: modelDetails.name,
        });
      });
    });
  });

  describe("notebook multi-stage data picker", () => {
    const ordersCardDetails = {
      name: "Card",
      type: "question",
      query: {
        "source-table": ORDERS_ID,
      },
    };

    const ordersCountCardDetails = {
      name: "Card",
      type: "question",
      query: {
        "source-table": ORDERS_ID,
        aggregation: [["count"]],
      },
    };

    const cardTypeToLabel = {
      question: "Saved Questions",
      model: "Models",
      metric: "Metrics",
    };

    /**
     *
     * @param {object} option
     * @param {boolean} [option.isMultiStageDataPicker]
     * @param {import("metabase/redux/store").InteractiveEmbeddingOptions} [option.searchParameters]
     */
    function startNewEmbeddingQuestion({
      isMultiStageDataPicker = false,
      searchParameters,
    } = {}) {
      H.visitFullAppEmbeddingUrl({
        url: "/",
        qs: {
          new_button: true,
          ...(isMultiStageDataPicker && { data_picker: "staged" }),
          ...searchParameters,
        },
      });
      cy.button("New").click();
      H.popover().findByText("Question").click();
    }

    const DEFAULT_ALIASES = {
      cardAlias: "@getCard",
      tableMetadataAlias: "@getTableMetadata",
    };

    function interceptDataPickerRequests(name) {
      cy.intercept("GET", "/api/card/*").as(`getCard${name}`);
      cy.intercept("GET", "/api/table/*/query_metadata").as(
        `getTableMetadata${name}`,
      );
      return {
        cardAlias: `@getCard${name}`,
        tableMetadataAlias: `@getTableMetadata${name}`,
      };
    }

    function selectTable({
      tableName,
      schemaName,
      databaseName,
      aliases = DEFAULT_ALIASES,
    }) {
      H.popover().within(() => {
        cy.findByText("Raw Data").click();
        if (databaseName) {
          cy.findByText(databaseName).click();
        }
        if (schemaName) {
          cy.findByText(schemaName).click();
        }
        cy.findByText(tableName).click();
      });
      cy.wait(aliases.tableMetadataAlias);
    }

    function selectCard({
      cardName,
      cardType,
      collectionNames,
      aliases = DEFAULT_ALIASES,
    }) {
      H.popover().within(() => {
        cy.findByText(cardTypeToLabel[cardType]).click();
        collectionNames.forEach((collectionName) =>
          cy.findByText(collectionName).click(),
        );
        cy.findByText(cardName).click();
      });
      cy.wait(aliases.tableMetadataAlias);
      if (cardType !== "metric") {
        cy.wait(aliases.cardAlias);
      }
    }

    function clickOnDataSource(sourceName) {
      H.getNotebookStep("data").findByText(sourceName).click();
    }

    function clickOnJoinDataSource(sourceName) {
      H.getNotebookStep("join")
        .findByLabelText("Right table")
        .findByText(sourceName)
        .click();
    }

    function verifyTableSelected({ tableName, schemaName, databaseName }) {
      H.popover().within(() => {
        cy.findByLabelText(tableName).should(
          "have.attr",
          "aria-selected",
          "true",
        );
        if (schemaName) {
          cy.findByText(schemaName).should("be.visible");
        }
        if (databaseName) {
          cy.findByText(databaseName).should("be.visible");
        }
      });
    }

    function verifyCardSelected({ cardName, collectionName }) {
      H.popover().within(() => {
        cy.findByText(collectionName).should("be.visible");
        cy.findByLabelText(cardName).should(
          "have.attr",
          "aria-selected",
          "true",
        );
      });
    }

    /**
     * Go back from the table selector to the bucket step (where it shows "Raw Data" and "Models").
     *
     * This step only shows when there are more than 1 option in the bucket step, the only time this happens
     * is when there are both selectable models and tables for the current user.
     */
    /** @param {'from-table' | 'from-model'} fromStep */
    function goBackToBucketStep(fromStep = "from-table") {
      H.popover().within(() => {
        cy.icon("chevronleft").click();
        if (fromStep === "from-table") {
          cy.icon("chevronleft").click();
        }
      });
    }

    beforeEach(() => {
      cy.signInAsNormalUser();
      cy.intercept("GET", "/api/card/*").as("getCard");
      cy.intercept("GET", "/api/table/*/query_metadata").as("getTableMetadata");
    });

    it('should respect "entity_types" search parameter and never offer questions or metrics (EMB-228)', () => {
      H.createQuestion({
        ...ordersCountCardDetails,
        type: "metric",
        collection_id: null,
      });
      cy.intercept({
        method: "GET",
        pathname: "/api/database",
        query: {
          saved: "true",
        },
      }).as("getDatabases");

      cy.log("test not providing `entity_types`");
      startNewEmbeddingQuestion({ isMultiStageDataPicker: true });
      cy.wait("@getDatabases");
      H.popover().within(() => {
        cy.findByText("Models").should("be.visible");
        cy.findByText("Raw Data").should("be.visible");
        cy.findByText("Saved Questions").should("not.exist");
        cy.findByText("Metrics").should("not.exist");
      });

      cy.log("test providing `entity_types` as an empty string");
      startNewEmbeddingQuestion({
        isMultiStageDataPicker: true,
        searchParameters: { entity_types: "" },
      });
      H.popover().within(() => {
        cy.findByText("Models").should("be.visible");
        cy.findByText("Raw Data").should("be.visible");
      });

      cy.log('test `entity_types=["table"]`');
      startNewEmbeddingQuestion({
        isMultiStageDataPicker: true,
        searchParameters: { entity_types: "table" },
      });
      H.popover().within(() => {
        /**
         * When we're in table step, it means we don't show models, otherwise, we would have shown
         * the bucket step which has "Raw Data" and "Models" options instead.
         */
        cy.findByText("Sample Database").should("be.visible");
        cy.findByRole("heading", { name: "Orders" }).should("be.visible");
        cy.findByRole("option", { name: "Orders" }).should("be.visible");
        cy.findByText("Models").should("not.exist");
      });

      // We don't have to test every permutations here because we already cover those cases in `EmbeddingDataPicker.unit.spec.tsx`
    });

    describe("table", () => {
      it(
        "should select a table when there are multiple databases (metabase#54127)",
        { tags: "@external" },
        () => {
          H.restore("postgres-12");
          cy.signInAsAdmin();
          H.createModelFromTableName({
            tableName: "orders",
            modelName: "Orders Model (Postgres)",
          });
          startNewEmbeddingQuestion({ isMultiStageDataPicker: true });
          selectTable({ tableName: "Orders", databaseName: "QA Postgres12" });
          clickOnDataSource("Orders");
          verifyTableSelected({
            tableName: "Orders",
            databaseName: "QA Postgres12",
          });

          cy.log(
            "assert that even after selecting a data source from one database, the data picker still shows the other data sources database",
          );
          H.popover().within(() => {
            cy.icon("chevronleft").click();
            cy.findByRole("heading", { name: "Sample Database" }).should(
              "be.visible",
            );
            cy.findByRole("heading", { name: "QA Postgres12" }).should(
              "be.visible",
            );

            cy.icon("chevronleft").click();
            cy.findByText("Models").click();
            cy.findByText("Orders Model").should("be.visible");
            cy.findByText("Orders Model (Postgres)").should("be.visible");
          });

          cy.log("close the data picker popover");
          cy.findByTestId("data-step-cell").click();

          cy.log(
            "assert that the tables should be filtered by the selected database from the starting data source.",
          );
          H.getNotebookStep("data").button("Join data").click();
          H.popover().within(() => {
            cy.icon("chevronleft").click();
            cy.findByRole("heading", { name: "Sample Database" }).should(
              "not.exist",
            );
            cy.findByRole("heading", { name: "QA Postgres12" }).should(
              "be.visible",
            );
          });

          cy.log(
            "assert that the models should be filtered by the selected database from the starting data source.",
          );
          H.popover().within(() => {
            cy.icon("chevronleft").click();
            cy.findByText("Models").click();
            cy.findByText("Orders Model").should("not.exist");
            cy.findByText("Orders Model (Postgres)").should("be.visible");
          });
        },
      );

      it(
        "should select a table in a schema-less database with the simple and staged data pickers",
        { tags: "@external" },
        () => {
          H.restore("mysql-8");
          cy.signInAsAdmin();

          cy.log("simple data picker");
          const simpleAliases = interceptDataPickerRequests("Simple");
          startNewEmbeddingQuestion();
          selectFirstDataSource("Reviews");
          cy.wait(simpleAliases.tableMetadataAlias).then(({ response }) => {
            expect(response.body.display_name).to.equal("Reviews");
            expect(response.body.db.name).to.equal("QA MySQL8");
          });

          cy.log("staged data picker");
          const stagedAliases = interceptDataPickerRequests("Staged");
          startNewEmbeddingQuestion({ isMultiStageDataPicker: true });
          selectTable({
            tableName: "Reviews",
            databaseName: "QA MySQL8",
            aliases: stagedAliases,
          });
          clickOnDataSource("Reviews");
          verifyTableSelected({
            tableName: "Reviews",
            databaseName: "QA MySQL8",
          });
        },
      );

      it(
        "should select a table when there are multiple schemas with the simple and staged data pickers",
        { tags: "@external" },
        () => {
          H.restore("postgres-writable");
          H.resetTestTable({ type: "postgres", table: "multi_schema" });
          cy.signInAsAdmin();
          H.resyncDatabase({ dbId: WRITABLE_DB_ID });

          cy.log("simple data picker");
          const simpleAliases = interceptDataPickerRequests("Simple");
          startNewEmbeddingQuestion();
          selectDataSource("Birds");
          cy.wait(simpleAliases.tableMetadataAlias).then(({ response }) => {
            expect(response.body.display_name).to.equal("Birds");
            expect(response.body.schema).to.equal("Wild");
            expect(response.body.db.name).to.equal("Writable Postgres12");
          });

          cy.log("staged data picker");
          const stagedAliases = interceptDataPickerRequests("Staged");
          startNewEmbeddingQuestion({ isMultiStageDataPicker: true });
          selectTable({
            tableName: "Animals",
            schemaName: "Domestic",
            databaseName: "Writable Postgres12",
            aliases: stagedAliases,
          });
          clickOnDataSource("Animals");
          verifyTableSelected({
            tableName: "Animals",
            schemaName: "Domestic",
            databaseName: "Writable Postgres12",
          });
        },
      );

      it("should join tables and models when the data source is a table", () => {
        const cardDetails = {
          ...ordersCardDetails,
          type: "model",
          collection_id: FIRST_COLLECTION_ID,
        };
        H.createQuestion(cardDetails);

        cy.log("select a table in the only database");
        const onlyDatabaseAliases = interceptDataPickerRequests("OnlyDatabase");
        startNewEmbeddingQuestion({ isMultiStageDataPicker: true });
        selectTable({ tableName: "Products", aliases: onlyDatabaseAliases });
        clickOnDataSource("Products");
        verifyTableSelected({
          tableName: "Products",
          databaseName: "Sample Database",
        });

        cy.log("join a table when the data source is a table");
        const joinTableAliases = interceptDataPickerRequests("JoinTable");
        startNewEmbeddingQuestion({ isMultiStageDataPicker: true });
        selectTable({
          tableName: "Orders",
          aliases: joinTableAliases,
        });
        H.getNotebookStep("data").button("Join data").click();
        H.popover().findByText("Products").click();
        clickOnJoinDataSource("Products");
        verifyTableSelected({
          tableName: "Products",
          databaseName: "Sample Database",
        });

        cy.log("join a model when the data source is a table");
        const joinModelAliases = interceptDataPickerRequests("JoinModel");
        startNewEmbeddingQuestion({ isMultiStageDataPicker: true });
        selectTable({
          tableName: "Products",
          aliases: joinModelAliases,
        });
        H.getNotebookStep("data").button("Join data").click();
        goBackToBucketStep();
        selectCard({
          cardName: cardDetails.name,
          cardType: "model",
          collectionNames: ["First collection"],
          aliases: joinModelAliases,
        });
        clickOnJoinDataSource(cardDetails.name);
        verifyCardSelected({
          cardName: cardDetails.name,
          collectionName: "First collection",
        });
      });
    });

    describe("model", () => {
      it("should select a model in every collection the user can see", () => {
        createCollectionMatrixCards({ withQuestions: false }).then(() => {
          COLLECTION_CASES.forEach((testCase, index) => {
            const modelName = getMatrixModelName(testCase.location);
            cy.log(`${testCase.user} user, model in ${testCase.location}`);

            signInForCollectionCase(testCase);
            const aliases = interceptDataPickerRequests(`Matrix${index}`);
            startNewEmbeddingQuestion({ isMultiStageDataPicker: true });
            selectCard({
              cardName: modelName,
              cardType: "model",
              collectionNames: testCase.stagedPath,
              aliases,
            });
            clickOnDataSource(modelName);
            verifyCardSelected({
              cardName: modelName,
              collectionName: testCase.stagedCollectionName,
            });
          });
        });
      });

      it("should join tables and models when the data source is a model", () => {
        // Orders Model already exists
        const ordersModelName = "Orders Model";
        const ordersCountModelDetails = {
          ...ordersCountCardDetails,
          name: "Orders Count Model",
          type: "model",
          collection_id: null,
        };
        H.createQuestion(ordersCountModelDetails);

        cy.log("join a model when the data source is a model");
        const joinModelAliases = interceptDataPickerRequests("JoinModel");
        startNewEmbeddingQuestion({ isMultiStageDataPicker: true });
        selectCard({
          cardName: ordersModelName,
          cardType: "model",
          collectionNames: [],
          aliases: joinModelAliases,
        });

        H.getNotebookStep("data").button("Join data").click();
        goBackToBucketStep("from-model");
        selectCard({
          cardName: ordersCountModelDetails.name,
          cardType: "model",
          collectionNames: [],
          aliases: joinModelAliases,
        });

        cy.log("select join column");
        H.popover().findByRole("option", { name: "ID" }).click();
        H.popover().findByRole("option", { name: "Count" }).click();

        clickOnJoinDataSource(ordersCountModelDetails.name);
        verifyCardSelected({
          cardName: ordersCountModelDetails.name,
          collectionName: "Our analytics",
        });

        cy.log("join a table when the data source is a model");
        const joinTableAliases = interceptDataPickerRequests("JoinTable");
        startNewEmbeddingQuestion({ isMultiStageDataPicker: true });
        selectCard({
          cardName: ordersModelName,
          cardType: "model",
          collectionNames: [],
          aliases: joinTableAliases,
        });

        H.getNotebookStep("data").button("Join data").click();
        goBackToBucketStep("from-model");

        selectTable({
          tableName: "Products",
          databaseName: "Sample Database",
          aliases: joinTableAliases,
        });
        clickOnJoinDataSource("Products");
        verifyTableSelected({
          tableName: "Products",
          databaseName: "Sample Database",
        });
      });
    });
  });

  describe("dashboards", () => {
    it("should show the dashboard header by default, send the 'X-Metabase-Client' header, and allow downloading question results when logged in via Google SSO (metabase#39848)", () => {
      const CSRF_TOKEN = "abcdefgh";
      cy.intercept("GET", "/api/user/current", (req) => {
        req.on("response", (res) => {
          res.headers["X-Metabase-Anti-CSRF-Token"] = CSRF_TOKEN;
        });
      });
      cy.intercept("POST", "/api/dashboard/*/dashcard/*/card/*/query/csv").as(
        "CsvDownload",
      );
      H.visitFullAppEmbeddingUrl({ url: `/dashboard/${ORDERS_DASHBOARD_ID}` });

      cy.wait("@getDashboard").then(({ request }) => {
        expect(request?.headers?.["x-metabase-client"]).to.equal(
          "embedding-iframe-full-app",
        );
      });
      cy.wait("@getDashCardQuery");

      cy.findByTestId("dashboard-name-heading").should("be.visible");
      cy.button(/Edited.*by/).should("be.visible");

      cy.log("hide the entity id in the dashboard info");
      H.dashboardHeader().findByRole("img", { name: /info/i }).click();
      H.sidesheet().within(() => {
        cy.findByRole("heading", { name: "Description" }).should("be.visible");
        cy.findByRole("heading", { name: /entity id/i }).should("not.exist");
      });
      H.sidesheet().findByLabelText("Close").click();
      H.sidesheet().should("not.exist");

      cy.log("download question results with the anti-CSRF token");
      H.getDashboardCard().realHover();
      H.getDashboardCardMenu().click();

      H.exportFromDashcard(".csv");

      cy.wait("@CsvDownload").then((interception) => {
        expect(
          interception.request.headers["x-metabase-anti-csrf-token"],
        ).to.equal(CSRF_TOKEN);
      });
    });

    it("should hide the dashboard header or its additional info by a param, and allow selecting tabs (metabase#38429, metabase#39002)", () => {
      cy.log("hide the dashboard header by a param");
      visitDashboardUrl({
        url: `/dashboard/${ORDERS_DASHBOARD_ID}`,
        qs: { header: false },
      });
      H.dashboardGrid().within(() => {
        H.assertTableRowsCount(2000);
      });
      cy.findByTestId("dashboard-header").should("not.exist");

      cy.log("hide the dashboard's additional info by a param");
      visitDashboardUrl({
        url: `/dashboard/${ORDERS_DASHBOARD_ID}`,
        qs: { additional_info: false },
      });
      // the app bar only shows breadcrumbs while the navbar is closed
      H.closeNavigationSidebar();

      cy.findByTestId("dashboard-header")
        .findByText("Orders in a dashboard")
        .should("be.visible");
      cy.findByTestId("dashboard-header")
        .findByText(/Edited/)
        .should("not.exist");
      cy.findByTestId("app-bar")
        .findByText("Our analytics")
        .should("be.visible");

      cy.log(
        "hide the dashboard with multiple tabs header by a param and allow selecting tabs",
      );
      const FIRST_TAB = { id: 1, name: "Tab 1" };
      const SECOND_TAB = { id: 2, name: "Tab 2" };
      H.createDashboardWithTabs({
        dashboard: {
          name: "Dashboard with tabs",
        },
        tabs: [FIRST_TAB, SECOND_TAB],
        dashcards: [
          createMockDashboardCard({
            dashboard_tab_id: FIRST_TAB.id,
            card_id: ORDERS_QUESTION_ID,
            size_x: 10,
            size_y: 8,
          }),
        ],
      }).then((dashboard) => {
        visitDashboardUrl({
          url: `/dashboard/${dashboard.id}`,
          qs: { header: false },
        });
      });
      H.dashboardGrid().within(() => {
        H.assertTableRowsCount(2000);
      });
      cy.findByTestId("dashboard-header").should("not.exist");
      H.goToTab(SECOND_TAB.name);
      cy.findByTestId("dashboard-empty-state").should("be.visible");
    });

    it("should preserve embedding options with click behavior (metabase#24756)", () => {
      addLinkClickBehavior({
        dashboardId: ORDERS_DASHBOARD_ID,
        linkTemplate: "/question/" + ORDERS_QUESTION_ID,
      });
      visitDashboardUrl({
        url: `/dashboard/${ORDERS_DASHBOARD_ID}`,
      });

      cy.findAllByRole("gridcell").first().click();
      cy.wait("@getCardQuery");

      // I don't know why this test starts to fail, but this command
      // will force the cursor to move away from the app bar, if
      // the cursor is still on the app bar, the logo will not be
      // be visible, since we'll only see the side bar toggle button.
      cy.findByTestId("question-filter-header").realHover();

      cy.findByTestId("main-logo").should("be.visible");
    });

    it("should have parameters header occupied the entire horizontal space when visiting a dashboard via navigation (metabase#30645)", () => {
      const filterId = "50c9eac6";
      const dashboardDetails = {
        name: "interactive dashboard embedding",
        parameters: [
          {
            id: filterId,
            name: "ID",
            slug: "id",
            type: "id",
          },
        ],
      };
      H.createDashboard(dashboardDetails).then(
        ({ body: { id: dashboardId } }) => {
          const textDashcard = H.getTextCardDetails({
            col: 0,
            row: 0,
            size_x: 6,
            size_y: 20,
            text: "I am a very long text card",
          });
          const dashcard = createMockDashboardCard({
            id: H.getNextUnsavedDashboardCardId(),
            col: 8,
            row: 0,
            card_id: ORDERS_QUESTION_ID,
            parameter_mappings: [
              {
                parameter_id: filterId,
                card_id: ORDERS_QUESTION_ID,
                target: [
                  "dimension",
                  ["field", ORDERS.ID, { "base-type": "type/Integer" }],
                ],
              },
            ],
          });
          H.updateDashboardCards({
            dashboard_id: dashboardId,
            cards: [dashcard, textDashcard],
          });
        },
      );

      H.visitFullAppEmbeddingUrl({ url: "/" });

      cy.log("Navigate to a dashboard via in-app navigation");
      H.navigationSidebar().findByText("Our analytics").click();
      cy.findByRole("main").findByText(dashboardDetails.name).click();
      H.navigationSidebar().should("be.visible");
      H.closeNavigationSidebar();

      cy.get("main header")
        .findByText(dashboardDetails.name)
        .should("be.visible");
      H.getDashboardCard()
        .findByText("I am a very long text card")
        .should("be.visible");

      // The bug won't appear if we scroll instantly and check the position of the dashboard parameter header.
      // I suspect that happens because we used to calculate the dashboard parameter header position in JavaScript,
      // which could take some time.
      const FPS = 1000 / 60;
      cy.findByRole("main").scrollTo("bottom", { duration: 2 * FPS });

      H.getDashboardCard()
        .findByText("I am a very long text card")
        .should("not.be.visible");
      cy.findByTestId("dashboard-parameters-widget-container").then(
        ($dashboardParameters) => {
          const dashboardParametersRect =
            $dashboardParameters[0].getBoundingClientRect();
          expect(dashboardParametersRect.x).to.equal(0);
        },
      );
    });

    describe("navigation through postMessage", () => {
      const assertIsLost = () => {
        cy.get("@iframeBody")
          .find("[role=status]")
          .should("contain", "We're a little lost");
      };

      const assertIsDashboard = () => {
        cy.get("@iframeBody")
          .find("[data-testid=table-footer]")
          .should("contain", "Showing first 2,000 rows");
      };

      const assertIsQuestion = () => {
        cy.get("@iframeBody")
          .find("[data-testid=question-row-count]")
          .should("contain", "Showing first 2,000 rows");
      };

      const goTo = (url) => {
        H.postMessageToIframe({
          iframeSelector: 'iframe[src*="localhost:4000/dashboard"]',
          messageData: {
            metabase: { type: "location", location: url },
          },
        });
      };

      it("should handle invalid questions/dashboards (metabase#65500)", () => {
        H.createDashboardWithTabs({
          dashboard: {
            name: "Dashboard with tabs",
          },
          dashcards: [
            createMockDashboardCard({
              card_id: ORDERS_QUESTION_ID,
              size_x: 10,
              size_y: 8,
            }),
          ],
        }).then((dashboard) => {
          H.loadInteractiveIframeEmbedTestPage({
            dashboardId: dashboard.id,
            iframeSelector: 'iframe[src*="localhost:4000/dashboard"]',
          });

          cy.get('iframe[src*="localhost:4000/dashboard"]')
            .its("0.contentDocument.body")
            .should("not.be.empty")
            .then(cy.wrap)
            .as("iframeBody");

          assertIsDashboard();

          // invalid dashboard -> valid dashboard
          goTo("/dashboard/9999990");
          assertIsLost();
          goTo(`/dashboard/${dashboard.id}`);
          assertIsDashboard();

          // invalid question -> valid question
          goTo("/question/9999990");
          assertIsLost();
          goTo(`/question/${ORDERS_QUESTION_ID}`);
          assertIsQuestion();

          // invalid question -> valid dashboard
          goTo("/question/9999990");
          assertIsLost();
          goTo(`/dashboard/${dashboard.id}`);
          assertIsDashboard();

          // invalid dashboard -> valid question
          goTo("/dashboard/9999990");
          assertIsLost();
          goTo(`/question/${ORDERS_QUESTION_ID}`);
          assertIsQuestion();
        });
      });
    });

    it("should keep the navbar open when navigating, and only close it when the user toggles it", () => {
      const dashboardName = "Navbar dashboard";
      H.createDashboard({ name: dashboardName });

      H.visitFullAppEmbeddingUrl({ url: "/" });
      H.navigationSidebar().should("be.visible");

      cy.log("navigating to a dashboard keeps the navbar open");
      H.navigationSidebar().findByText("Our analytics").click();
      cy.findByRole("main").findByText(dashboardName).click();
      cy.findByTestId("dashboard-name-heading").should(
        "have.value",
        dashboardName,
      );
      H.navigationSidebar().should("be.visible");
      H.appBar().findByText("Our analytics").should("not.be.visible");

      cy.log("the toggle closes the navbar, and it stays closed on navigation");
      H.appBar().findByTestId("sidebar-toggle").click();
      H.navigationSidebar().should("not.be.visible");
      H.appBar().findByText("Our analytics").click();
      cy.findByTestId("collection-name-heading").should(
        "have.text",
        "Our analytics",
      );
      H.navigationSidebar().should("not.be.visible");
    });

    it("should send `frame` message with dashboard height when the dashboard is resized (metabase#37437)", () => {
      const TAB_1 = { id: 1, name: "Tab 1" };
      const TAB_2 = { id: 2, name: "Tab 2" };
      H.createDashboardWithTabs({
        tabs: [TAB_1, TAB_2],
        name: "Dashboard",
        dashcards: [
          createMockTextDashboardCard({
            dashboard_tab_id: TAB_1.id,
            size_x: 10,
            size_y: 20,
            text: "I am a text card",
          }),
        ],
      }).then((dashboard) => {
        H.visitFullAppEmbeddingUrl({
          url: `/dashboard/${dashboard.id}`,
          onBeforeLoad(window) {
            cy.spy(window.parent, "postMessage").as("postMessage");
          },
        });
      });

      // TODO: Find a way to assert that this is the last call.
      cy.get("@postMessage").should("have.been.calledWith", {
        metabase: {
          type: "frame",
          frame: {
            mode: "fit",
            height: Cypress.sinon.match((value) => value > 1000),
          },
        },
      });

      cy.get("@postMessage").invoke("resetHistory");
      cy.findByRole("tab", { name: TAB_2.name }).click();
      cy.get("@postMessage").should("have.been.calledWith", {
        metabase: {
          type: "frame",
          frame: {
            mode: "fit",
            height: Cypress.sinon.match((value) => value < 1000),
          },
        },
      });

      // the app bar only shows breadcrumbs while the navbar is closed
      H.closeNavigationSidebar();
      cy.get("@postMessage").invoke("resetHistory");
      cy.findByTestId("app-bar").findByText("Our analytics").click();

      cy.findByRole("heading", { name: "Usage analytics" }).should(
        "be.visible",
      );
      cy.get("@postMessage").should("have.been.calledWith", {
        metabase: {
          type: "frame",
          frame: {
            mode: "fit",
            height: 800,
          },
        },
      });
    });
  });

  describe("x-ray dashboards", () => {
    it("should show the dashboard header by default and hide it by a param", () => {
      visitXrayDashboardUrl({ url: "/auto/dashboard/table/1" });

      cy.findByRole("heading", { name: "More X-rays" }).should("be.visible");
      cy.button("Save this").should("be.visible");

      cy.log("hide the dashboard header by a param");
      visitXrayDashboardUrl({
        url: "/auto/dashboard/table/1",
        qs: { header: false },
      });

      cy.findByRole("heading", { name: "More X-rays" }).should("be.visible");
      cy.button("Save this").should("not.exist");
    });
  });

  describe("documents > comments", () => {
    it("should not display comments in an embedded app", () => {
      const DOCUMENT_ID = 1;
      const PARAGRAPH_ID = "b7fa322a-964e-d668-8d30-c772ef4f0022";

      H.createDocument({
        idAlias: "documentId",
        name: "Lorem ipsum",
        document: {
          type: "doc",
          content: [
            {
              type: "paragraph",
              attrs: {
                _id: PARAGRAPH_ID,
              },
              content: [
                {
                  type: "text",
                  text: "Lorem ipsum dolor sit amet.",
                },
              ],
            },
          ],
        },
      });
      H.createComment({
        target_type: "document",
        target_id: DOCUMENT_ID,
        child_target_id: PARAGRAPH_ID,
        parent_comment_id: null,
        content: {
          type: "doc",
          content: [
            {
              type: "paragraph",
              attrs: { _id: uuid() },
              content: [{ type: "text", text: "Test comment" }],
            },
          ],
        },
        html: "<p>Test comment</p>",
      });

      cy.intercept({
        method: "GET",
        path: "/api/document/*",
      }).as("documentGet");

      cy.intercept({
        method: "GET",
        pathname: "/api/comment",
      }).as("commentGet");

      H.visitFullAppEmbeddingUrl({
        url: `/document/${DOCUMENT_ID}`,
      });

      cy.wait("@documentGet");
      H.documentContent().should("contain.text", "Lorem ipsum dolor sit amet.");

      cy.findByLabelText("Show all comments").should("not.exist");

      cy.findAllByRole("link", { name: "Comments" }).should("not.exist");

      cy.get("@commentGet.all").should("have.length", 0);
    });
  });
});

describe("scenarios > embedding > full app - jwt sso integration", () => {
  /**
   * These tests are meant to validate the JWT SSO flow.
   *
   * We need to mock the JWT provider url even though we only care to check the
   * redirect URL, this is because if the request fails, cypress will see
   * `chrome-error://chromewebdata/` as the url.
   */
  const baseUrl = Cypress.config("baseUrl");
  const dashboardId = ORDERS_DASHBOARD_ID;
  const jwtSecret =
    "0000000000000000000000000000000000000000000000000000000000000000";

  beforeEach(() => {
    H.restore();
    cy.signInAsAdmin();
    H.activateToken("pro-self-hosted");
    // enable interactive embedding
    H.updateSetting("enable-embedding-interactive", true);
    H.updateSetting("embedding-app-origins-interactive", "http://localhost:*");
    H.updateSetting("embedding-secret-key", jwtSecret);

    // setup jwt
    H.updateSetting(
      "jwt-identity-provider-uri",
      "http://localhost:8888/jwt-provider",
    );
    H.updateSetting("jwt-shared-secret", jwtSecret);
    H.updateSetting("jwt-enabled", true);

    cy.intercept("POST", `/api/card/${ORDERS_QUESTION_ID}/query`).as(
      "getCardQuery",
    );
    addLinkClickBehavior({
      dashboardId,
      linkTemplate: "/question/{{test_attribute}}",
    });

    cy.signOut(); // we *need* to sign out, otherwise the SSO process won't kick in
  });

  it("should pass the path via return_to to the jwt provider when un-authenticated, then authenticate the user and pass JWT user attributes to click behavior custom destinations (metabase#65942)", () => {
    cy.log(
      "pass the path via return_to to the jwt provider when un-authenticated",
    );
    cy.intercept(/http:\/\/localhost:8888\/.*/, (req) => {
      req.reply({
        statusCode: 200,
        body: "ok",
      });
    }).as("jwt-provider");

    H.visitFullAppEmbeddingUrl({ url: `/dashboard/${dashboardId}` });

    cy.wait("@jwt-provider").then((interception) => {
      expect(interception.request.url).to.equal(
        `http://localhost:8888/jwt-provider?return_to=/dashboard/${dashboardId}`,
      );
    });

    cy.log(
      "authenticate the user and pass JWT user attributes to click behavior custom destinations",
    );
    const jwtAttributeValue = ORDERS_QUESTION_ID;

    // 1) set up a click behavior that uses a user attribute in the URL
    // Added in beforeeach so it uses the admin user

    // 2) sign a jwt for the user with a custom attribute
    cy.task("signJwt", {
      payload: {
        email: USERS.normal.email,
        exp: Math.round(Date.now() / 1000) + 10 * 60,
        test_attribute: jwtAttributeValue,
      },
      secret: jwtSecret,
    }).then((jwtToken) => {
      // 3) mock the JWT provider to redirect to the auth/sso endpoint with the JWT
      cy.intercept(/http:\/\/localhost:8888\/.*/, (req) => {
        const redirectUrl = `${baseUrl}/auth/sso?jwt=${jwtToken}&return_to=/dashboard/${dashboardId}`;
        req.redirect(redirectUrl);
      }).as("jwt-provider-redirect");
    });

    // 4) visit the dashboard as embedded
    H.visitFullAppEmbeddingUrl({ url: `/dashboard/${dashboardId}` });

    cy.wait("@jwt-provider-redirect");

    // 5) verify user is on dashboard
    cy.url().should("equal", `${baseUrl}/dashboard/${dashboardId}`);
    H.main().findByText("Orders in a dashboard").should("be.visible");

    cy.findAllByRole("gridcell").first().click();
    cy.wait("@getCardQuery");

    cy.findByTestId("question-filter-header").realHover();
    cy.findByTestId("main-logo").should("be.visible");
  });
});

const visitQuestionUrl = (urlOptions) => {
  H.visitFullAppEmbeddingUrl(urlOptions);
  cy.wait("@getCardQuery");
};

const visitDashboardUrl = (urlOptions) => {
  H.visitFullAppEmbeddingUrl(urlOptions);
  cy.wait("@getDashboard");
  cy.wait("@getDashCardQuery");
};

const visitXrayDashboardUrl = (urlOptions) => {
  H.visitFullAppEmbeddingUrl(urlOptions);
  cy.wait("@getXrayDashboard");
};

const addLinkClickBehavior = ({ dashboardId, linkTemplate }) => {
  cy.request("GET", `/api/dashboard/${dashboardId}`).then(({ body }) => {
    cy.request("PUT", `/api/dashboard/${dashboardId}`, {
      dashcards: body.dashcards.map((card) => ({
        ...card,
        visualization_settings: {
          column_settings: {
            '["name","ID"]': {
              click_behavior: {
                type: "link",
                linkType: "url",
                linkTemplate,
              },
            },
          },
        },
      })),
    });
  });
};

const sideNav = () => {
  return cy.findByTestId("main-navbar-root");
};

const selectDataSource = (dataSource) => {
  H.popover().findByRole("link", { name: dataSource }).click();
};

/**
 *
 * @param {string} dataSource  When using with QA database, the first option would be the table from the QA database.
 */
const selectFirstDataSource = (dataSource) => {
  H.popover().findAllByRole("link", { name: dataSource }).first().click();
};

const MATRIX_LOCATIONS = [
  { location: "root", collectionId: null },
  { location: "First", collectionId: FIRST_COLLECTION_ID },
  { location: "Second", collectionId: SECOND_COLLECTION_ID },
  { location: "personal", collectionId: NORMAL_PERSONAL_COLLECTION_ID },
  { location: "Third", collectionId: THIRD_COLLECTION_ID },
];

const COLLECTION_CASES = [
  {
    user: "normal",
    location: "root",
    collectionName: "Our analytics",
    stagedPath: [],
    stagedCollectionName: "Our analytics",
  },
  {
    user: "normal",
    location: "First",
    collectionName: "First collection",
    stagedPath: ["First collection"],
    stagedCollectionName: "First collection",
  },
  {
    user: "normal",
    location: "Second",
    collectionName: "Second collection",
    stagedPath: ["First collection", "Second collection"],
    stagedCollectionName: "Second collection",
  },
  {
    user: "normal",
    location: "personal",
    collectionName: "Robert Tableton's Personal Collection",
    stagedPath: ["Your personal collection"],
    stagedCollectionName: "Your personal collection",
  },
  {
    user: "admin",
    location: "personal",
    collectionName: "Robert Tableton's Personal Collection",
    stagedPath: [
      "All personal collections",
      "Robert Tableton's Personal Collection",
    ],
    stagedCollectionName: "Robert Tableton's Personal Collection",
  },
  {
    user: "nocollection",
    location: "First",
    readCollectionIds: [FIRST_COLLECTION_ID],
    collectionName: "First collection",
    stagedPath: ["First collection"],
    stagedCollectionName: "First collection",
  },
  {
    user: "nocollection",
    location: "Third",
    readCollectionIds: [FIRST_COLLECTION_ID, THIRD_COLLECTION_ID],
    collectionName: "Third collection",
    stagedPath: ["Third collection"],
    stagedCollectionName: "Third collection",
  },
];

const getMatrixModelName = (location) => `Model in ${location}`;

const getMatrixQuestionName = (location) => `Question in ${location}`;

const createCollectionMatrixCards = ({ withQuestions }) => {
  const modelIds = {};
  cy.signInAsAdmin();
  MATRIX_LOCATIONS.forEach(({ location, collectionId }) => {
    H.createQuestion({
      name: getMatrixModelName(location),
      type: "model",
      query: { "source-table": ORDERS_ID },
      collection_id: collectionId,
    }).then(({ body }) => {
      modelIds[location] = body.id;
    });
    if (withQuestions) {
      H.createQuestion({
        name: getMatrixQuestionName(location),
        type: "question",
        query: { "source-table": ORDERS_ID },
        collection_id: collectionId,
      });
    }
  });
  return cy.wrap(modelIds);
};

const signInForCollectionCase = ({ user, readCollectionIds }) => {
  if (readCollectionIds) {
    cy.signInAsAdmin();
    cy.updateCollectionGraph({
      [ALL_USERS_GROUP]: Object.fromEntries(
        readCollectionIds.map((collectionId) => [collectionId, "read"]),
      ),
    });
  }
  cy.signIn(user);
};

describe("issue 51934 (EMB-189)", () => {
  const COLLECTION_NAME = "Model Collection";
  const MODEL_IN_ROOT_NAME = "Products Model";
  const MODEL_IN_COLLECTION_NAME = "QA Postgres12 Orders Model";
  const QUESTION_IN_COLLECTION_NAME = "Orders Question";

  beforeEach(() => {
    H.restore("postgres-12");
    cy.signInAsAdmin();
    H.activateToken("pro-self-hosted");
    H.createModelFromTableName({
      tableName: "products",
      modelName: MODEL_IN_ROOT_NAME,
    });
    H.createCollection({
      name: COLLECTION_NAME,
      alias: "collectionId",
    });
    H.createModelFromTableName({
      tableName: "orders",
      modelName: MODEL_IN_COLLECTION_NAME,
      idAlias: "modelId",
    });
    moveToCollection({
      collectionIdAlias: "collectionId",
      cardIdAlias: "modelId",
    });
    H.createQuestion(
      {
        name: QUESTION_IN_COLLECTION_NAME,
        query: {
          "source-table": ORDERS_ID,
        },
      },
      {
        wrapId: true,
        idAlias: "questionId",
      },
    );
    moveToCollection({
      collectionIdAlias: "collectionId",
      cardIdAlias: "questionId",
    });
  });

  it("should set the starting join step based on the query source", () => {
    startNewEmbeddingQuestion();
    const QA_DB_NAME = "QA Postgres12";
    const DATA_SOURCE_NAME = "Orders";

    // Before the picker can auto-navigate into the data source's collection it
    // resolves the target path asynchronously: a card-metadata fetch plus one
    // `listCollectionItems` request per collection level (root -> Model
    // Collection). On a throttled CI runner that serial chain routinely outlasts
    // Cypress's default 4 s command timeout, so the picker is still showing the
    // parent (root) collections when a default-timeout query gives up — the
    // dominant "cannot find menuitem '...' (only the root collections are
    // present)" flake. Wait for the loader to clear, then give the item lookup a
    // generous timeout so it waits for the path to finish resolving, and assert
    // it is visible (positive anchor) before clicking.
    const PICKER_ITEM_TIMEOUT = 15000;
    const clickPickerItem = (name) => {
      cy.get('[data-testid="mini-picker-list-loader"]').should("not.exist");
      cy.findByRole("menuitem", { name }, { timeout: PICKER_ITEM_TIMEOUT })
        .should("be.visible")
        .click();
    };

    // The data-source picker and the join picker are both rendered by the same
    // embedding DataSourceSelector, so a generic popover query could not tell
    // them apart. When a click swaps one for the other they can briefly overlap
    // (the outgoing one is still in its close transition while the incoming one
    // is already mounted), which made matching ambiguous and flaky on slow CI
    // runners.
    //
    // Each picker now carries its trigger's label as the dropdown's accessible
    // name (`aria-label`), so we can target each popover deterministically by
    // name regardless of any transition overlap. `.filter(":visible").last()`
    // guards against a same-named popover that is still animating closed.
    const pickerPopover = (name) =>
      cy
        .get(`[data-element-id=mantine-popover][aria-label="${name}"]`)
        .filter(":visible")
        .should("have.length.at.least", 1)
        .last();
    const dataSourcePopover = () => pickerPopover("Pick your starting data");
    const joinPopover = () => pickerPopover("Pick data to join");

    cy.log("select a table as a data source");
    dataSourcePopover().within(() => {
      cy.findByText("Raw Data").click();
    });
    dataSourcePopover().within(() => {
      cy.findByRole("heading", { name: QA_DB_NAME }).click();
    });
    dataSourcePopover().within(() => {
      cy.findByRole("option", { name: DATA_SOURCE_NAME }).click();
    });
    H.getNotebookStep("data").button("Join data").click();

    cy.log(
      'select the "Join" step when the data source is a table will open a table in the same database',
    );
    joinPopover().within(() => {
      cy.findByText(QA_DB_NAME).should("be.visible");
      cy.findByRole("option", { name: "Orders" }).should("be.visible");
    });

    cy.log(
      "changing the data source while not selecting the join step should refresh the data picker on the join step",
    );
    H.getNotebookStep("data").findByText(DATA_SOURCE_NAME).click();

    cy.log('go back to the "Bucket" step');
    dataSourcePopover().within(() => {
      cy.icon("chevronleft").click();
    });
    dataSourcePopover().within(() => {
      cy.icon("chevronleft").click();
    });

    cy.log(
      "select a question as a data source should open the saved question step in the same collection as the data source (metabase#58357)",
    );
    dataSourcePopover().within(() => {
      cy.findByText("Saved Questions").click();
    });
    dataSourcePopover().within(() => clickPickerItem(COLLECTION_NAME));
    dataSourcePopover().within(() =>
      clickPickerItem(QUESTION_IN_COLLECTION_NAME),
    );

    cy.log("the join popover is automatically opened");
    joinPopover().within(() => {
      cy.log("the collection of the data source should be selected");
      cy.findByRole("menuitem", { name: COLLECTION_NAME }).should(
        "have.css",
        "background-color",
        // brand color
        "rgb(80, 158, 226)",
      );
      clickPickerItem(QUESTION_IN_COLLECTION_NAME);
    });

    cy.log(
      "select a model as a data source should open the model step in the same collection as the data source",
    );
    H.getNotebookStep("data").findByText(QUESTION_IN_COLLECTION_NAME).click();

    // Go back to the "Bucket" step
    dataSourcePopover().within(() => {
      cy.findByText("Saved Questions").click();
    });
    // We're now at the "Bucket" step
    dataSourcePopover().within(() => {
      cy.findByText("Models").click();
    });
    dataSourcePopover().within(() => clickPickerItem(MODEL_IN_COLLECTION_NAME));

    cy.log("the join popover is automatically opened");
    joinPopover().within(() => {
      cy.log("the collection of the data source should be selected");
      cy.findByRole("menuitem", { name: COLLECTION_NAME }).should(
        "have.css",
        "background-color",
        // brand color
        "rgb(80, 158, 226)",
      );
      clickPickerItem(MODEL_IN_COLLECTION_NAME);
    });

    cy.log(
      "select a data source after selecting a join step should refresh the data picker on the join step",
    );
    H.getNotebookStep("data").findByText(MODEL_IN_COLLECTION_NAME).click();
    dataSourcePopover().within(() => clickPickerItem("Our analytics"));
    dataSourcePopover().within(() => clickPickerItem(MODEL_IN_ROOT_NAME));

    joinPopover().within(() => {
      cy.log("the collection of the new data source should be selected");
      cy.findByRole("menuitem", { name: "Our analytics" }).should(
        "have.css",
        "background-color",
        // brand color
        "rgb(80, 158, 226)",
      );
      cy.findByRole("menuitem", { name: MODEL_IN_ROOT_NAME }).should(
        "be.visible",
      );
    });
  });

  function startNewEmbeddingQuestion() {
    H.visitFullAppEmbeddingUrl({
      url: "/question/notebook",
      qs: {
        data_picker: "staged",
        entity_types: "table,model,question",
      },
    });
  }

  function moveToCollection({ collectionIdAlias, cardIdAlias }) {
    cy.get(`@${collectionIdAlias}`).then((collectionId) => {
      cy.get(`@${cardIdAlias}`).then((cardId) => {
        cy.request("PUT", `/api/card/${cardId}`, {
          collection_id: collectionId,
        });
      });
    });
  }
});