Skip to content

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

59.0 KB
Raw Blame
const { H } = cy;
import { SAMPLE_DB_ID, USER_GROUPS } from "e2e/support/cypress_data";
import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";
import { b64hash_to_utf8 } from "metabase/utils/encoding";
import { PIVOT_TABLE_BODY_LABEL } from "metabase/visualizations/visualizations/PivotTable/constants";

const {
  ORDERS,
  ORDERS_ID,
  PRODUCTS,
  PRODUCTS_ID,
  PEOPLE,
  REVIEWS,
  REVIEWS_ID,
} = SAMPLE_DATABASE;

const QUESTION_NAME = "Cypress Pivot Table";
const DASHBOARD_NAME = "Pivot Table Dashboard";

const TEST_CASES = [
  { case: "question", subject: QUESTION_NAME, confirmSave: false },
  { case: "dashboard", subject: DASHBOARD_NAME, confirmSave: false },
];

describe("scenarios > visualizations > pivot tables", { tags: "@slow" }, () => {
  beforeEach(() => {
    H.restore();
    cy.signInAsAdmin();
  });

  it("should not show sub-total data after a switch to other viz type", () => {
    createTestQuestion();
    cy.findByTestId("query-visualization-root").within(() => {
      assertOnPivotFields();
    });

    // Switch to "ordinary" table
    cy.findByTestId("view-footer").findByText("Visualization").click();
    H.sidebar().icon("table2").should("be.visible").click();

    cy.findByTestId("app-bar").within(() => {
      cy.findByText("Started from");
      cy.findByText(QUESTION_NAME);
    });

    cy.log("Assertions on a table itself");
    H.tableInteractive().should("be.visible");
    cy.findByTestId("pivot-table").should("not.exist");
    cy.findByTestId("query-visualization-root").within(() => {
      cy.findByText(/Users? → Source/);
      cy.findByText("783"); // Affiliate - Doohickey
      cy.findByText("986"); // Twitter - Gizmo
      cy.findByText(/Row totals/i).should("not.exist");
      cy.findByText(/Grand totals/i).should("not.exist");
      cy.findByText("3,520").should("not.exist");
      cy.findByText("4,784").should("not.exist");
      cy.findByText("18,760").should("not.exist");
    });
  });

  it("should allow drill through on cells and on left/top header values", () => {
    createTestQuestion({ wrapId: true });

    cy.log("Drill through on a cell");
    // open drill-through menu
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("783").click();
    // drill through to orders list
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("See these Orders").click();
    // filters are applied
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("User → Source is Affiliate");
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("Product → Category is Doohickey");
    // data loads
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("45.04");

    cy.log("Drill through on header values");
    H.visitQuestion("@questionId");
    // open drill-through menu and filter to that value
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("Doohickey").click();
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    H.popover().within(() => cy.findByText("=").click());
    // filter is applied
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("Product → Category is Doohickey");
    // filter out affiliate as a source
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("Affiliate").click();
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    H.popover().within(() => cy.findByText("≠").click());
    // filter is applied and value is gone from the left header
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("User → Source is not Affiliate");
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("Affiliate").should("not.exist");
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("3,193"); // new grand total
  });

  it("should rearrange pivoted columns", () => {
    createTestQuestion();

    // Open Pivot table side-bar
    H.openVizSettingsSidebar();

    // Give it some time to open the side-bar fully before we start dragging
    assertOnPivotSettings();

    // Drag the second aggregate (Product category) from table columns to table rows
    H.moveDnDKitListElement("drag-handle", {
      startIndex: 1,
      dropIndex: 0,
    });

    // One field should now be empty
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("Drag fields here");

    cy.log("Implicit assertions on a table itself");
    cy.findByTestId("query-visualization-root").within(() => {
      cy.findByText(/Products? → Category/);
      cy.findByText(/Users? → Source/);
      cy.findByText("Count");
      cy.findByText(/Totals for Doohickey/i);
      cy.findByText("3,976");
    });
  });

  it("should be able to use binned numeric dimensions as rows (metabase#14136) and as only columns (metabase#44500)", () => {
    // Sample database Orders > Count by Subtotal: Auto binned
    H.visitQuestionAdhoc({
      dataset_query: {
        type: "query",
        query: {
          "source-table": ORDERS_ID,
          aggregation: [["count"]],
          breakout: [
            ["field", ORDERS.SUBTOTAL, { binning: { strategy: "default" } }],
          ],
        },
        database: SAMPLE_DB_ID,
      },
      display: "pivot",
      visualization_settings: {},
    });

    cy.findByTestId("query-visualization-root").within(() => {
      cy.findByText("Subtotal: 8 bins");
      cy.findByText("Count");
      cy.findByText("2,720");
      cy.findByText(/Grand totals/i);
      cy.findByText("18,760");
    });

    cy.log("Binned dimensions as pivot columns with no rows");
    H.visitQuestionAdhoc({
      dataset_query: {
        type: "query",
        query: {
          "source-table": ORDERS_ID,
          aggregation: [["count"]],
          breakout: [
            ["field", ORDERS.SUBTOTAL, { binning: { strategy: "default" } }],
            ["field", ORDERS.TAX, { binning: { strategy: "default" } }],
          ],
        },
        database: SAMPLE_DB_ID,
      },
      display: "pivot",
      visualization_settings: {
        "pivot_table.column_split": {
          rows: [],
          columns: ["SUBTOTAL", "TAX"],
          values: ["count"],
        },
      },
    });

    getPivotTableBodyCell(0).should("have.text", "34");
    getPivotTableBodyCell(1).should("have.text", "1,594");
    getPivotTableBodyCell(2).should("have.text", "823");
    getPivotTableBodyCell(3).should("have.text", "974");
    getPivotTableBodyCell(4).should("have.text", "3,104");
  });

  it("should allow collapsing rows", () => {
    // open a pivot table of order count grouped by source, category x year
    const b1 = ["field", ORDERS.CREATED_AT, { "temporal-unit": "year" }];
    const b2 = [
      "field",
      PRODUCTS.CATEGORY,
      { "source-field": ORDERS.PRODUCT_ID },
    ];
    const b3 = ["field", PEOPLE.SOURCE, { "source-field": ORDERS.USER_ID }];

    H.visitQuestionAdhoc({
      dataset_query: {
        type: "query",
        query: {
          "source-table": ORDERS_ID,
          aggregation: [["count"]],
          breakout: [b1, b2, b3],
        },
        database: SAMPLE_DB_ID,
      },
      display: "pivot",
      visualization_settings: {
        "pivot_table.column_split": {
          rows: ["CATEGORY", "SOURCE"],
          columns: ["CREATED_AT"],
          values: ["count"],
        },
      },
    });

    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("215"); // see a non-subtotal value
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("294"); // see a value in another section

    // click to collapse rows
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("Doohickey").parent().find(".Icon-dash").click();
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("1,352"); // subtotal is still there
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("215").should("not.exist"); // value is hidden

    // click to uncollapse
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("Totals for Doohickey").parent().find(".Icon-add").click();
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("215"); // ...and it's back!

    // collapse the column
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("Product → Category").parent().find(".Icon-dash").click();
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("215").should("not.exist"); // value is hidden
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("294").should("not.exist"); // value in another section is also hidden

    // uncollapse Doohickey
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("Totals for Doohickey").parent().find(".Icon-add").click();
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("215"); // value in doohickey is visible
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("294").should("not.exist"); // the other one is still hidden
  });

  describe("issue 50346", () => {
    const questionDetails = {
      query: {
        "source-table": ORDERS_ID,
        aggregation: [
          ["count"],
          ["sum", ["field", ORDERS.TOTAL, { "base-type": "type/Float" }]],
        ],
        breakout: [
          [
            "field",
            PRODUCTS.CATEGORY,
            { "base-type": "type/Text", "source-field": ORDERS.PRODUCT_ID },
          ],
          [
            "field",
            PRODUCTS.VENDOR,
            { "base-type": "type/Text", "source-field": ORDERS.PRODUCT_ID },
          ],
          [
            "field",
            PEOPLE.SOURCE,
            { "base-type": "type/Text", "source-field": ORDERS.USER_ID },
          ],
        ],
      },
      display: "pivot",
      visualization_settings: {
        "pivot_table.column_split": {
          // mix field refs with and without `base-type` to make sure we support both cases
          rows: [
            ["field", PRODUCTS.CATEGORY, { "source-field": ORDERS.PRODUCT_ID }],
            [
              "field",
              PRODUCTS.VENDOR,
              { "base-type": "type/Text", "source-field": ORDERS.PRODUCT_ID },
            ],
            [
              "field",
              PEOPLE.SOURCE,
              { "base-type": "type/Text", "source-field": ORDERS.USER_ID },
            ],
          ],
          columns: [],
          values: [
            ["aggregation", 0],
            ["aggregation", 1],
          ],
        },
        "pivot_table.column_widths": {
          leftHeaderWidths: [150, 214, 120],
          totalLeftHeaderWidths: 484,
          valueHeaderWidths: {},
        },
      },
    };

    const groupValue = "Annetta Wyman and Sons";
    const totalValue = "1,217.76";

    beforeEach(() => {
      cy.signInAsNormalUser();
      cy.intercept("PUT", "/api/card/*").as("updateCard");
    });

    it("should be able to collapse rows for questions with legacy pivot settings (metabase#50346)", () => {
      H.createQuestion(questionDetails, { visitQuestion: true, wrapId: true });

      cy.log("collapse one of the sections");
      cy.findByTestId("pivot-table").within(() => {
        cy.findByText(totalValue).should("be.visible");
        cy.findByTestId(`${groupValue}-toggle-button`).click();
        cy.findByText(totalValue).should("not.exist");
      });

      cy.log("save and make sure the setting is preserved on reload");
      H.queryBuilderHeader().button("Save").click();
      H.modal().button("Save").click();
      cy.wait("@updateCard");
      H.visitQuestion("@questionId");
      cy.findByTestId("pivot-table").within(() => {
        cy.findByText(totalValue).should("not.exist");
      });

      cy.log("expand the section");
      cy.findByTestId("pivot-table").within(() => {
        cy.findByTestId(`${groupValue}-toggle-button`).click();
        cy.findByText(totalValue).should("be.visible");
      });
    });
  });

  it("should show standalone values when collapsed to the sub-level grouping (metabase#25250) and to the top-level grouping (metabase#15211)", () => {
    const questionDetails = {
      name: "25250",
      dataset_query: {
        type: "query",
        query: {
          "source-table": ORDERS_ID,
          filter: ["<", ["field", ORDERS.CREATED_AT, null], "2025-06-01"],
          aggregation: [["count"]],
          breakout: [
            ["field", ORDERS.CREATED_AT, { "temporal-unit": "month" }],
            ["field", ORDERS.USER_ID, null],
            ["field", ORDERS.PRODUCT_ID, null],
          ],
        },
        database: SAMPLE_DB_ID,
      },
      display: "pivot",
      visualization_settings: {
        "pivot_table.column_split": {
          rows: ["CREATED_AT", "USER_ID", "PRODUCT_ID"],
          columns: [],
          values: ["count"],
        },
        "pivot_table.collapsed_rows": {
          value: [],
          rows: ["CREATED_AT", "USER_ID", "PRODUCT_ID"],
        },
      },
    };

    H.visitQuestionAdhoc(questionDetails);
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("1162").should("be.visible");
    // Collapse "User ID" column
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("User ID").parent().find(".Icon-dash").click();
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("Totals for 1162").should("be.visible");

    //Expanding the grouped column should still work
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("Totals for 1162").parent().find(".Icon-add").click();
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("1162").should("be.visible");
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("34").should("be.visible");

    cy.log("Collapse the top-level grouping");
    H.visitQuestionAdhoc({
      dataset_query: {
        type: "query",
        query: {
          "source-table": ORDERS_ID,
          aggregation: [["sum", ["field", ORDERS.DISCOUNT, null]], ["count"]],
          breakout: [
            ["field", ORDERS.CREATED_AT, { "temporal-unit": "day" }],
            ["field", ORDERS.PRODUCT_ID, null],
          ],
          filter: [
            "and",
            [
              "between",
              ["field", ORDERS.CREATED_AT, null],
              "2025-11-09",
              "2025-11-11",
            ],
            ["!=", ["field", ORDERS.PRODUCT_ID, null], 146],
          ],
        },
        database: SAMPLE_DB_ID,
      },
      display: "pivot",
      visualization_settings: {
        "pivot_table.column_split": {
          rows: ["CREATED_AT", "PRODUCT_ID"],
          columns: [],
          values: ["sum", "count"],
        },
        "pivot_table.collapsed_rows": {
          value: [],
          rows: ["CREATED_AT", "PRODUCT_ID"],
        },
      },
    });

    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("November 9, 2025");
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("November 10, 2025");
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("November 11, 2025");
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("Totals for November 10, 2025").should("not.exist");
    collapseRowsFor("Created At: Day");
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("Totals for November 9, 2025");
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("Totals for November 10, 2025");
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("Totals for November 11, 2025");

    function collapseRowsFor(column_name) {
      cy.findByText(column_name).parent().find(".Icon-dash").click();
    }
  });

  it("should allow hiding subtotals and uncollapse a value when hiding them", () => {
    H.visitQuestionAdhoc({
      dataset_query: testQuery,
      display: "pivot",
      visualization_settings: {
        "pivot_table.column_split": {
          rows: ["SOURCE", "CATEGORY"],
          columns: [],
          values: [],
        },
      },
    });

    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText(/Count by Users? → Source and Products? → Category/); // ad-hoc title

    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("3,520"); // check for one of the subtotals

    // open settings
    H.openVizSettingsSidebar();
    assertOnPivotSettings();

    // Confirm that Product -> Category doesn't have the option to hide subtotals
    openColumnSettings("Product → Category");
    H.popover().findByText("Show totals").should("not.exist");

    // turn off subtotals for User -> Source
    openColumnSettings("User → Source");
    cy.findByTestId(
      "chart-settings-widget-pivot_table.column_show_totals",
    ).within(() => {
      cy.findByText("Show totals").should("be.visible");
      cy.findByRole("switch").click({ force: true });
    });

    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("3,520").should("not.exist"); // the subtotal has disappeared!

    cy.log("Collapse a value with subtotals shown");
    cy.findByTestId("chart-settings-widget-pivot_table.column_show_totals")
      .findByRole("switch")
      .click({ force: true });
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("3,520"); // affiliate subtotal is back
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("899");
    cy.findByTestId("pivot-table")
      .findByTestId("Affiliate-toggle-button")
      .click();
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("899").should("not.exist"); // "Affiliate" is collapsed
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("3,520");

    cy.log("Hiding subtotals uncollapses the value");
    openColumnSettings("User → Source");
    cy.findByTestId("chart-settings-widget-pivot_table.column_show_totals")
      .findByRole("switch")
      .click({ force: true });
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("3,520").should("not.exist"); // the subtotal isn't there
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("899"); // Affiliate is no longer collapsed
  });

  it("pivot table should show subtotals for a group of a single value (metabase#52333)", () => {
    const baseQuery = `
SELECT *
FROM (
  SELECT
    category,
    source,
    state,
    SUM(orders.discount) AS discount,
    SUM(orders.total) AS total,
    SUM(orders.quantity) AS quantity
  FROM
    orders
    LEFT JOIN products ON orders.product_id = products.id
    LEFT JOIN people ON orders.user_id = people.id
  GROUP BY category, source, state
) AS filtered_orders
WHERE NOT (
  category = 'Gizmo'
  AND (
    source IN ('Facebook', 'Google', 'Organic', 'Twitter')
    OR state NOT IN ('AK')
  )
);`;

    const baseQuestionDetails = {
      name: "52333",
      display: "table",
      native: {
        query: baseQuery,
      },
    };

    H.createNativeQuestion(baseQuestionDetails, {
      visitQuestion: true,
      wrapId: true,
    });

    cy.get("@questionId").then((id) => {
      const questionDetails = {
        query: {
          "source-table": `card__${id}`,
          aggregation: [["count"]],
          breakout: [
            [
              "field",
              "CATEGORY",
              {
                "base-type": "type/Text",
              },
            ],
            [
              "field",
              "SOURCE",
              {
                "base-type": "type/Text",
              },
            ],
            [
              "field",
              "STATE",
              {
                "base-type": "type/Text",
              },
            ],
          ],
        },
        display: "pivot",
        visualization_settings: {
          "pivot_table.column_split": {
            rows: ["CATEGORY", "SOURCE", "STATE"],
            columns: [],
            values: ["count", "avg"],
          },
          "pivot_table.column_widths": {
            leftHeaderWidths: [104, 92, 80],
            totalLeftHeaderWidths: 276,
            valueHeaderWidths: {},
          },
          "pivot_table.collapsed_rows": {
            value: ['["Doohickey"]', '["Gadget"]', '["Widget"]'],
            rows: ["CATEGORY", "SOURCE", "STATE"],
          },
        },
      };

      H.createQuestion(questionDetails, { visitQuestion: true });
    });

    H.queryBuilderMain().within(() => {
      cy.findByText("Affiliate");
      cy.findByText("AK");

      // Ensure it does not show subtotals for the single value by default
      cy.findByText("Totals for Affiliate").should("not.exist");

      H.openVizSettingsSidebar();
    });

    H.sidebar().findByText("Condense duplicate totals").click();

    // Ensure it shows subtotals for the single value
    H.queryBuilderMain()
      .findByText("Totals for Affiliate")
      .should("be.visible");
  });

  it("should be created from an ad-hoc question and allow formatting and resizing columns", () => {
    H.visitQuestionAdhoc({ dataset_query: testQuery, display: "pivot" });

    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText(/Count by Users? → Source and Products? → Category/); // ad-hoc title
    cy.findByTestId("query-visualization-root").within(() => {
      assertOnPivotFields();
    });

    H.openVizSettingsSidebar();
    assertOnPivotSettings();
    openColumnSettings("Count");

    cy.log("New panel for the column options");
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("Column title");
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("Style");
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("Separator style");

    cy.log("Value fields cannot be sorted");
    H.popover().findByText("Sort order").should("not.exist");

    cy.log("Change the value formatting");
    cy.findByDisplayValue("Normal").click();
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("Percent").click();
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("Done").click();
    cy.findByTestId("query-visualization-root").within(() => {
      cy.findByText("78,300%");
    });

    cy.log("Change the title of a row column");
    H.openVizSettingsSidebar();
    openColumnSettings("User → Source");
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText(/Column title/);
    cy.get("input[id=column_title]").clear().type("ModifiedTITLE").blur();
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("Done").click();
    cy.findByTestId("query-visualization-root").within(() => {
      cy.findByText("ModifiedTITLE");
    });

    cy.log("Resize columns and persist the sizes");
    cy.findAllByTestId("pivot-table-resize-handle")
      .first()
      .as("leftHeaderColHandle");
    // eslint-disable-next-line metabase/no-unsafe-element-filtering
    cy.findAllByTestId("pivot-table-resize-handle")
      .last()
      .as("totalHeaderColHandle");

    H.moveDnDKitElementByAlias("@leftHeaderColHandle", {
      horizontal: -100,
      vertical: 0,
    });

    H.moveDnDKitElementByAlias("@totalHeaderColHandle", {
      horizontal: 100,
      vertical: 0,
    });
    cy.findByTestId("pivot-table").within(() => {
      cy.findByText("ModifiedTITLE").should(($headerTextEl) => {
        expect(getCellWidth($headerTextEl)).equal(80); // min width is 80
      });
      cy.findByText("Row totals").should(($headerTextEl) => {
        expect(getCellWidth($headerTextEl)).equal(220);
      });
    });

    H.saveQuestion(undefined, undefined, {
      path: ["Our analytics"],
    });

    cy.reload(); // reload to make sure the settings are persisted
    cy.findByTestId("pivot-table").within(() => {
      cy.findByText("78,300%");
      cy.findByText("ModifiedTITLE").should(($headerTextEl) => {
        expect(getCellWidth($headerTextEl)).equal(80);
      });
      cy.findByText("Row totals").should(($headerTextEl) => {
        expect(getCellWidth($headerTextEl)).equal(220);
      });
    });
  });

  it("should be able to change field name used for values (metabase#15353)", () => {
    cy.intercept("POST", "/api/dataset/pivot").as("pivotDataset");
    H.createQuestion(
      {
        name: "15353",
        query: {
          "source-table": ORDERS_ID,
          aggregation: [["count"]],
          breakout: [["field", ORDERS.CREATED_AT, { "temporal-unit": "year" }]],
        },
        display: "pivot",
      },
      { visitQuestion: true },
    );

    H.openVizSettingsSidebar();
    openColumnSettings("Count");
    cy.findByDisplayValue("Count").type(" renamed").blur();
    cy.wait("@pivotDataset");

    cy.findByTestId("query-visualization-root").should(
      "contain",
      "Count renamed",
    );
  });

  it("should allow sorting fields", () => {
    // Pivot by a single column with many values (100 bins).
    // Having many values hides values that are sorted to the end.
    // This lets us assert on presence of a certain value.
    H.visitQuestionAdhoc({
      dataset_query: {
        type: "query",
        query: {
          "source-table": ORDERS_ID,
          aggregation: [["count"]],
          breakout: [
            [
              "field",
              ORDERS.TOTAL,
              { binning: { strategy: "num-bins", "num-bins": 100 } },
            ],
          ],
        },
        database: SAMPLE_DB_ID,
      },
      display: "pivot",
    });

    // open settings and expand Total column settings
    H.openVizSettingsSidebar();

    sortColumnResults("Total: 100 bins", "descending");
    cy.findAllByTestId("pivot-table").within(() => {
      cy.findByText("158 – 160").should("be.visible");
      cy.findByText("8 – 10").should("not.exist");
    });

    sortColumnResults("Total: 100 bins", "ascending");
    cy.findAllByTestId("pivot-table").within(() => {
      cy.findByText("8 – 10").should("be.visible");
      cy.findByText("158 – 160").should("not.exist");
    });
  });

  it("should display an error message for native queries", () => {
    H.visitQuestionAdhoc({
      dataset_query: {
        type: "native",
        native: { query: "select 1", "template-tags": {} },
        database: SAMPLE_DB_ID,
      },
      display: "pivot",
      visualization_settings: {},
    });

    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText(
      "Pivot tables are only supported for questions built in the query builder.",
    );
  });

  describe("dashboards", () => {
    it("should be scrollable even when tiny (metabase#24678)", () => {
      H.createQuestionAndDashboard({
        questionDetails: {
          name: QUESTION_NAME,
          query: testQuery.query,
          display: "pivot",
        },
        dashboardDetails: {
          name: DASHBOARD_NAME,
        },
        cardDetails: {
          size_x: 3,
          size_y: 3,
        },
      }).then(({ body: { dashboard_id } }) => H.visitDashboard(dashboard_id));

      H.dashboardCards()
        .eq(0)
        .within(() => {
          cy.findByText("Doohickey").scrollIntoView().should("be.visible");
        });
    });

    it("should allow filtering drill through (metabase#14632) (metabase#14465) and hide an empty pivot dashcard (UXW-4145)", () => {
      const FILTER_ID = "d7988e02";

      H.createQuestionAndDashboard({
        questionDetails: {
          name: QUESTION_NAME,
          query: testQuery.query,
          display: "pivot",
        },
        dashboardDetails: {
          name: DASHBOARD_NAME,
        },
        cardDetails: {
          size_x: 16,
          size_y: 8,
        },
      }).then(({ body: { id, card_id, dashboard_id } }) => {
        cy.log(
          "Add an ID filter to the dashboard and map it to the pivot card",
        );
        cy.request("PUT", `/api/dashboard/${dashboard_id}`, {
          parameters: [{ id: FILTER_ID, name: "ID", slug: "id", type: "id" }],
          dashcards: [
            {
              id,
              card_id,
              row: 0,
              col: 0,
              size_x: 16,
              size_y: 8,
              parameter_mappings: [
                {
                  parameter_id: FILTER_ID,
                  card_id,
                  target: ["dimension", ["field", ORDERS.ID]],
                },
              ],
            },
          ],
        });
        cy.wrap(dashboard_id).as("dashboardId");
        H.visitDashboard(dashboard_id);
      });

      cy.log("Drill through a header value adds a filter");
      assertOnPivotFields();
      // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
      cy.findByText("Google").click(); // open drill-through menu
      // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
      H.popover().within(() => cy.findByText("=").click()); // drill with additional filter
      // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
      cy.findByText("User → Source is Google"); // filter was added
      // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
      cy.findByText("Row totals"); // it's still a pivot table
      // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
      cy.findByText("1,027"); // primary data value
      // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
      cy.findByText("3,798"); // subtotal value

      H.visitDashboard("@dashboardId");

      cy.log("Filtering to a value with no rows shows the no-results state");
      H.filterWidget().click();
      H.dashboardParametersPopover().within(() => {
        cy.findByPlaceholderText("Enter an ID").type("-1{enter}");
        cy.button("Add filter").click();
      });
      // Pre-fix this rendered a blank pivot; the grand-total row hid the emptiness.
      H.getDashboardCard(0).findByText("No results").should("be.visible");

      cy.log("Enabling 'hide if empty' removes the now-empty card");
      H.editDashboard();
      cy.findByTestId("dashboardcard-actions-panel").within(() => {
        cy.icon("palette").click({ force: true });
      });
      cy.findByRole("dialog").within(() => {
        cy.findByLabelText("Hide this card if there are no results").click({
          force: true,
        });
        cy.button("Done").click();
      });
      H.saveDashboard();

      cy.findByTestId("dashcard").should("not.exist");
    });

    it("should allow mapping pivot table dashcard fields to click behavior targets (metabase#52339)", () => {
      const questionDetails = {
        name: "Orders, Distinct values of ID, Grouped by Product → Title and Created At (month) and User → ID",

        query: {
          "source-table": ORDERS_ID,
          aggregation: [["distinct", ["field", ORDERS.ID, null]]],
          breakout: [
            ["field", PRODUCTS.TITLE, { "source-field": ORDERS.PRODUCT_ID }],
            ["field", PEOPLE.SOURCE, { "source-field": ORDERS.USER_ID }],
          ],
        },
        display: "pivot",
        visualization_settings: {
          "pivot_table.column_split": {
            rows: ["TITLE", "SOURCE"],
            columns: [],
            values: ["distinct"],
          },
        },
      };

      const sourceParam = {
        name: "Source",
        slug: "filter-text",
        id: "1b9cd9f1",
        type: "string/=",
        sectionId: "string",
      };

      H.createQuestionAndDashboard({
        dashboardDetails: {
          parameters: [sourceParam],
        },
        questionDetails,
        cardDetails: {
          size_x: 16,
          size_y: 8,
        },
      }).then(({ body: { id, card_id, dashboard_id }, questionId }) => {
        cy.wrap(questionId).as("questionId");

        cy.request("PUT", `/api/dashboard/${dashboard_id}`, {
          dashcards: [
            {
              id,
              card_id,
              row: 0,
              col: 0,
              size_x: 16,
              size_y: 8,
              series: [],
              visualization_settings: {},
              parameter_mappings: [
                {
                  parameter_id: sourceParam.id,
                  card_id,
                  target: [
                    "dimension",
                    [
                      "field",
                      PEOPLE.SOURCE,
                      {
                        "source-field": ORDERS.USER_ID,
                      },
                    ],
                  ],
                },
              ],
            },
          ],
        });

        H.visitDashboard(dashboard_id);
      });

      H.editDashboard();
      H.getDashboardCard(0)
        .realHover({ scrollBehavior: "bottom" })
        .findByLabelText("Click behavior")
        .click();

      H.sidebar().within(() => {
        cy.findByText("Go to a custom destination").click();
        cy.findByText("Dashboard").click();
      });

      H.modal().findByText("Test Dashboard").click();

      cy.findByTestId("click-mappings").findByText("Source").click();

      H.popover().within(() => {
        cy.findByText("Product → Title");
        cy.findByText("User → Source");
        cy.findByText("Distinct values of ID");
      });
    });
  });

  describe("sharing (metabase#14447)", () => {
    beforeEach(() => {
      cy.viewport(1400, 800); // Row totals on embed preview was getting cut off at the normal width
      cy.log("Create a question");

      H.createQuestionAndDashboard({
        questionDetails: {
          name: QUESTION_NAME,
          query: testQuery.query,
          display: "pivot",
        },
        dashboardDetails: {
          name: DASHBOARD_NAME,
        },
        cardDetails: {
          size_x: 16,
          size_y: 8,
        },
      }).then(({ body: { card_id, dashboard_id } }) => {
        cy.log("Enable sharing on card");
        cy.request("POST", `/api/card/${card_id}/public_link`);

        cy.log("Enable embedding on card");
        cy.request("PUT", `/api/card/${card_id}`, {
          enable_embedding: true,
        });

        cy.log("Enable sharing on dashboard");
        cy.request("POST", `/api/dashboard/${dashboard_id}/public_link`);

        cy.log("Enable embedding on dashboard");
        cy.request("PUT", `/api/dashboard/${dashboard_id}`, {
          enable_embedding: true,
        });

        cy.wrap(card_id).as("questionId");
        cy.wrap(dashboard_id).as("dashboardId");
      });
    });

    TEST_CASES.forEach((test) => {
      describe(test.case, () => {
        it("should display pivot table in an embed URL and a public link", () => {
          cy.visit("collection/root");
          // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
          cy.findByText(test.subject).click();
          cy.findByTestId("pivot-table").should("be.visible");
          if (test.case === "question") {
            H.openSharingMenu();
            H.modal().within(() => {
              cy.findByText("Save").click();
            });
          }
          H.openSharingMenu(/public link/i);
          cy.findByTestId("public-link-popover-content")
            .findByTestId("public-link-input")
            .invoke("val")
            .as("publicLink", { type: "static" });
          cy.get("body").click("topLeft");
          cy.findByTestId("public-link-popover-content").should("not.exist");

          const { alias, resource } = {
            question: {
              alias: "@questionId",
              resource: "question",
            },
            dashboard: {
              alias: "@dashboardId",
              resource: "dashboard",
            },
          }[test.case];

          cy.get(alias).then((id) => {
            H.openLegacyStaticEmbeddingModal({
              resource: resource,
              resourceId: id,
              activeTab: "parameters",
              confirmSave: test.confirmSave,
              unpublishBeforeOpen: false,
            });
          });

          // visit the iframe src directly to ensure it's not sing preview endpoints
          H.visitIframe();

          cy.findByTestId("embed-frame-header").contains(test.subject);
          assertOnPivotFields();

          cy.get("@publicLink").then((publicLink) => cy.visit(publicLink));
          cy.findByTestId("embed-frame-header").contains(test.subject);
          assertOnPivotFields();
        });
      });
    });
  });

  it("should show a download widget with a hint about pivoted xlsx exports (metabase#14750)", () => {
    const HINT_TEXT =
      "Trying to pivot this data in Excel? You should download the raw data instead.";
    createTestQuestion();
    cy.icon("download").click();

    H.popover().within(() => {
      cy.findByText(".xlsx").click();
      cy.findByText(HINT_TEXT);
      cy.findByText("Read the docs").should(
        "have.attr",
        "href",
        "https://www.metabase.com/docs/latest/questions/exporting-results.html#exporting-pivot-tables",
      );

      cy.findByLabelText("Close hint").click();
      cy.findByText(HINT_TEXT).should("not.exist");

      cy.findByText("Download");
    });

    // Ensure the hint is not visible after a page reload
    cy.reload();

    cy.icon("download").click();
    H.popover().within(() => {
      cy.findByText(".xlsx").click();
      cy.findByLabelText(".xlsx").should("be.checked");
      cy.findByText(HINT_TEXT).should("not.exist");
    });
  });

  it("should work with custom mapping of display values (metabase#14985)", () => {
    cy.intercept("POST", "/api/dataset/pivot").as("datasetPivot");

    cy.log("Remap 'Reviews Rating' display values to custom values");
    cy.request("POST", `/api/field/${REVIEWS.RATING}/dimension`, {
      name: "Rating",
      type: "internal",
      human_readable_field_id: null,
    });

    cy.request("POST", `/api/field/${REVIEWS.RATING}/values`, {
      values: [
        [1, "A"],
        [2, "B"],
        [3, "C"],
        [4, "D"],
        [5, "E"],
      ],
    });

    H.visitQuestionAdhoc({
      dataset_query: {
        database: SAMPLE_DB_ID,
        query: {
          "source-table": REVIEWS_ID,
          aggregation: [["count"]],
          breakout: [
            ["field-id", REVIEWS.RATING],
            ["datetime-field", ["field-id", REVIEWS.CREATED_AT], "year"],
          ],
        },
        type: "query",
      },
      display: "line",
    });

    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("Visualization").click();
    H.leftSidebar().within(() => {
      // This part is still failing. Uncomment when fixed.
      // cy.findByText("Pivot Table")
      //   .parent()
      //   .should("have.css", "opacity", "1");
      cy.findByTestId("more-charts-toggle").click();
      cy.icon("pivot_table").click({ force: true });
    });

    cy.wait("@datasetPivot");
    cy.findByTestId("query-visualization-root").within(() => {
      cy.contains("Row totals");
      cy.findByText("333"); // Row totals for 2027
      cy.findByText("Grand totals");
    });
  });

  it("should not show subtotals for flat tables and apply conditional formatting", () => {
    H.visitQuestionAdhoc({
      dataset_query: {
        type: "query",
        query: {
          "source-table": ORDERS_ID,
          aggregation: [["sum", ["field", ORDERS.SUBTOTAL, null]]],
          breakout: [
            ["field", ORDERS.CREATED_AT, { "temporal-unit": "year" }],
            ["field", PRODUCTS.CATEGORY, { "source-field": ORDERS.PRODUCT_ID }],
            ["field", PEOPLE.STATE, { "source-field": ORDERS.USER_ID }],
          ],
          filter: [">", ["field", ORDERS.CREATED_AT, null], "2029-01-01"],
        },
        database: SAMPLE_DB_ID,
      },
      display: "pivot",
      visualization_settings: {
        "pivot_table.column_split": {
          rows: ["STATE", "CREATED_AT"],
          columns: ["CATEGORY"],
          values: ["sum"],
        },
        "pivot_table.collapsed_rows": {
          value: [],
          rows: ["STATE", "CREATED_AT"],
        },
      },
    });

    cy.log("A single year per state means no subtotals");
    cy.findByTestId("pivot-table").should("contain", "65.09");
    cy.findAllByText(/Totals for .*/i).should("have.length", 0);

    H.openVizSettingsSidebar();
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("Conditional Formatting").click();

    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("Add a rule").click();
    cy.findByTestId("conditional-formatting-value-input").type("70").blur();
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("is equal to").click({ force: true });
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("is less than or equal to").click({ force: true });

    cy.contains("[data-testid=pivot-table-cell]", "65.09").should(
      "have.css",
      "background-color",
      "rgba(80, 158, 227, 0.65)",
    );
  });

  it("should sort by metric (metabase#22872)", () => {
    const questionDetails = {
      dataset_query: {
        database: SAMPLE_DB_ID,
        query: {
          "source-table": REVIEWS_ID,
          aggregation: [["count"]],
          breakout: [
            ["field", REVIEWS.RATING, { "base-type": "type/Integer" }],
            [
              "field",
              REVIEWS.CREATED_AT,
              {
                "temporal-unit": "year",
                "base-type": "type/DateTimeWithLocalTZ",
              },
            ],
          ],
        },
        type: "query",
      },
      display: "pivot",
    };

    H.visitQuestionAdhoc(questionDetails);

    cy.findByTextEnsureVisible("Created At: Year");
    cy.findByTextEnsureVisible("Row totals");

    assertTopMostRowTotalValue("149");

    H.openNotebook();

    cy.findByTextEnsureVisible("Sort").click();

    H.popover().contains("Count").click();
    cy.wait("@pivotDataset");

    cy.button("Visualize").click();

    assertTopMostRowTotalValue("23");

    /**
     * @param { string } value
     */
    function assertTopMostRowTotalValue(value) {
      // Warning: Fragile selector!
      // TODO: refactor once we have a better HTML structure for tables.
      cy.get("[role=row] > div").eq(5).invoke("text").should("eq", value);
    }
  });

  it("should be horizontally scrollable when columns overflow", () => {
    const createdAtField = [
      "field",
      REVIEWS.CREATED_AT,
      {
        "temporal-unit": "month",
        "base-type": "type/DateTimeWithLocalTZ",
      },
    ];
    const ratingField = [
      "field",
      REVIEWS.RATING,
      { "base-type": "type/Integer" },
    ];

    const query = {
      "source-table": REVIEWS_ID,
      aggregation: [["count"]],
      breakout: [createdAtField, ratingField],
    };

    const vizSettings = {
      "pivot_table.column_split": {
        rows: ["RATING"],
        columns: ["CREATED_AT"],
        values: ["count"],
      },
    };

    H.createQuestionAndDashboard({
      questionDetails: {
        name: QUESTION_NAME,
        query,
        display: "pivot",
        visualization_settings: vizSettings,
      },
      dashboardDetails: {
        name: DASHBOARD_NAME,
      },
      cardDetails: {
        size_x: 16,
        size_y: 8,
      },
    }).then(({ body: { dashboard_id }, questionId }) => {
      cy.wrap(questionId).as("questionId");
      H.visitDashboard(dashboard_id);
    });

    H.dashboardCards().within(() => {
      cy.findByLabelText(PIVOT_TABLE_BODY_LABEL).scrollTo(10000, 0);
      cy.findByText("Row totals").should("be.visible");
    });

    cy.get("@questionId").then((id) => H.visitQuestion(id));

    H.queryBuilderMain().within(() => {
      cy.findByLabelText(PIVOT_TABLE_BODY_LABEL).scrollTo(10000, 0);
      cy.findByText("Row totals").should("be.visible");
    });
  });

  describe("column resizing", () => {
    const QUESTION_37726 = {
      name: "Pivot table with custom column width",
      display: "pivot",
      query: {
        "source-table": ORDERS_ID,
        breakout: [
          [
            "field",
            ORDERS.TOTAL,
            { "base-type": "type/Float", binnig: { strategy: "default" } },
          ],
        ],
        aggregation: [
          [
            "distinct",
            ["field", ORDERS.ID, { "base-type": "type/BigInteger" }],
          ],
        ],
      },
      visualization_settings: {
        "pivot_table.column_split": {
          rows: ["TOTAL"],
          columns: [],
          values: ["distinct"],
        },
        "pivot_table.column_widths": {
          leftHeaderWidths: [80],
          totalLeftHeaderWidths: 80,
          valueHeaderWidths: { 0: 193 },
        },
      },
    };

    const QUESTION_42697 = {
      display: "pivot",
      query: {
        "source-table": ORDERS_ID,
        aggregation: [
          ["count"],
          ["sum", ["field", ORDERS.TOTAL, { "base-type": "type/Float" }]],
        ],
        breakout: [
          [
            "field",
            PEOPLE.STATE,
            { "base-type": "type/Text", "source-field": ORDERS.USER_ID },
          ],
          [
            "field",
            ORDERS.CREATED_AT,
            { "base-type": "type/DateTime", "temporal-unit": "year" },
          ],
        ],
      },
      visualization_settings: {
        "pivot_table.column_split": {
          rows: ["CREATED_AT"],
          columns: ["STATE"],
          values: ["count", "sum"],
        },
        "pivot_table.column_widths": {
          leftHeaderWidths: [156],
          totalLeftHeaderWidths: 156,
          valueHeaderWidths: {},
        },
      },
    };

    beforeEach(() => {
      cy.signInAsNormalUser();
      cy.intercept("PUT", "/api/card/*").as("updateCard");
    });

    it("should display a pivot table with custom column widths when a breakout is added (metabase#37726) (metabase#42697)", () => {
      cy.log(
        "Add a breakout from the summarize sidebar and reload (metabase#37726)",
      );
      cy.intercept("POST", "/api/dataset/pivot").as("pivot");

      // The important data point in this question is that it has custom
      // leftHeaderWidths as if a user had dragged them to change the defaults.
      H.createQuestion(QUESTION_37726, { visitQuestion: true });

      // Now, add in another column to the pivot table
      cy.button(/Summarize/).click();

      cy.findByRole("listitem", { name: "Category" })
        .realHover()
        .button("Add dimension")
        .click();

      // Wait for the pivot call to return
      cy.wait("@pivot");

      // Refresh the page -- this loads the question using the transient value
      cy.reload();

      // Look for the new column name in the resulting pivot table.
      // Note that before this fix, the page would error out and this elements,
      // along with the rest of the pivot table, would not appear.
      // Instead, you got a nice ⚠️ icon and a "Something's gone wrong" tooltip.
      H.main().within(() => {
        cy.findByText("Product → Category", { timeout: 8000 });
      });

      cy.log("Add a breakout in the notebook and save (metabase#42697)");
      H.createQuestion(QUESTION_42697, { visitQuestion: true });
      H.openNotebook();
      H.getNotebookStep("summarize")
        .findByTestId("breakout-step")
        .icon("add")
        .click();
      H.popover().within(() => {
        cy.findByText("Product").click();
        cy.findByText("Category").click();
      });
      H.queryBuilderHeader().findByText("Save").click();
      H.modal().button("Save").click();
      cy.wait("@updateCard");
      cy.button("Visualize").click();
      cy.findByTestId("pivot-table")
        .findByText("Product → Category")
        .should("be.visible");
    });
  });

  it("should not have to wait for data to show fields in summarisation (metabase#26467)", () => {
    cy.intercept("POST", "api/card/pivot/*/query", (req) => {
      req.on("response", (res) => {
        res.setDelay(20_000);
      });
    });

    createTestQuestion({ visitQuestion: false }).then(({ body }) => {
      // manually visiting the question to avoid the auto wait logic,
      // we need to go to the editor while the query is still loading
      cy.visit(`/question/${body.id}`);
    });

    // confirm that it's loading
    H.main().findByText("Doing science...").should("be.visible");

    H.openNotebook();

    H.main().findByText("User → Source").click();

    H.popover().findByText("Address").click();

    H.main().findByText("User → Address").should("be.visible");
  });

  describe("issue 37380", () => {
    beforeEach(() => {
      const categoryField = [
        "field",
        PRODUCTS.CATEGORY,
        { "base-type": "type/Text" },
      ];

      const createdAtField = [
        "field",
        PRODUCTS.CREATED_AT,
        {
          "base-type": "type/DateTime",
          "temporal-unit": "month",
        },
      ];

      // to reproduce metabase#37380 it's important that user has access to the database, but not to the table
      cy.updatePermissionsGraph({
        [USER_GROUPS.DATA_GROUP]: {
          [SAMPLE_DB_ID]: {
            "create-queries": {
              PUBLIC: {
                [PRODUCTS_ID]: "no",
              },
            },
          },
        },
      });

      H.createQuestion(
        {
          query: {
            "source-table": PRODUCTS_ID,
            aggregation: ["count"],
            breakout: [categoryField, createdAtField],
          },
          display: "pivot",
          visualization_settings: {
            "pivot_table.column_split": {
              rows: ["CREATED_AT"],
              columns: ["CATEGORY"],
              values: ["count"],
            },
            "pivot_table.column_widths": {
              leftHeaderWidths: [141],
              totalLeftHeaderWidths: 141,
              valueHeaderWidths: {},
            },
          },
        },
        {
          wrapId: true,
          idAlias: "questionId",
        },
      );
    });

    it("does not allow users with no table access to update pivot questions (metabase#37380)", () => {
      cy.signInAsNormalUser();
      H.visitQuestion("@questionId");
      H.openVizSettingsSidebar();
      cy.findByLabelText("Show row totals").click({ force: true });

      cy.findByTestId("qb-save-button").should("have.attr", "data-disabled");
    });
  });

  describe("issue 38265", () => {
    beforeEach(() => {
      H.createQuestion(
        {
          query: {
            "source-table": ORDERS_ID,
            aggregation: [
              ["count"],
              [
                "sum",
                ["field", ORDERS.SUBTOTAL, { "base-type": "type/Float" }],
              ],
            ],
            breakout: [
              [
                "field",
                ORDERS.CREATED_AT,
                { "base-type": "type/DateTime", "temporal-unit": "month" },
              ],
              [
                "field",
                PEOPLE.STATE,
                { "base-type": "type/Text", "source-field": ORDERS.USER_ID },
              ],
              [
                "field",
                PRODUCTS.CATEGORY,
                { "base-type": "type/Text", "source-field": ORDERS.PRODUCT_ID },
              ],
            ],
          },
          display: "pivot",
        },
        {
          visitQuestion: true,
        },
      );
    });

    it("correctly filters the query when zooming in on a **row** header (metabase#38265)", () => {
      cy.findByTestId("pivot-table").findByText("KS").click();
      H.popover().findByText("Zoom in: State").click();

      cy.log("Filter pills");
      cy.findByTestId("filter-pill").should("have.text", "User → State is KS");

      cy.log("Pivot table column headings");
      cy.findByTestId("pivot-table")
        .should("contain", "Created At: Month")
        .and("contain", "User → Latitude")
        .and("contain", "User → Longitude");
    });
  });

  it("should be possible to switch between notebook and simple views when pivot table is the visualization (metabase#39504)", () => {
    H.visitQuestionAdhoc({
      dataset_query: {
        database: SAMPLE_DB_ID,
        query: {
          "source-table": ORDERS_ID,
          aggregation: [
            [
              "sum",
              [
                "field",
                ORDERS.SUBTOTAL,
                {
                  "base-type": "type/Float",
                },
              ],
            ],
            [
              "sum",
              [
                "field",
                ORDERS.TOTAL,
                {
                  "base-type": "type/Float",
                },
              ],
            ],
          ],
          breakout: [
            [
              "field",
              PEOPLE.SOURCE,
              {
                "base-type": "type/Text",
                "source-field": ORDERS.USER_ID,
              },
            ],
          ],
        },
        type: "query",
      },
    });

    cy.log("Set the visualization to pivot table using the UI");
    cy.intercept("POST", "/api/dataset/pivot").as("pivotDataset");
    H.openVizTypeSidebar();
    cy.findByTestId("Pivot Table-button").click();
    cy.wait("@pivotDataset");
    cy.findByTestId("pivot-table")
      .should("contain", "User → Source")
      .and("contain", "Sum of Subtotal")
      .and("contain", "Sum of Total")
      .and("contain", "Grand totals");

    H.openNotebook();
    H.getNotebookStep("summarize")
      .should("be.visible")
      .and("contain", "Sum of Subtotal")
      .and("contain", "Sum of Total");

    // Close the notebook editor
    H.openNotebook();
    H.getNotebookStep("summarize").should("not.exist");
    cy.findByTestId("pivot-table")
      .should("be.visible")
      .and("contain", "User → Source")
      .and("contain", "Sum of Subtotal")
      .and("contain", "Sum of Total")
      .and("contain", "Grand totals");
  });

  it("displays total values for collapsed rows (metabase#26919)", () => {
    const categoryField = [
      "field",
      PRODUCTS.CATEGORY,
      { "base-type": "type/Text" },
    ];

    H.createQuestion(
      {
        display: "pivot",
        query: {
          "source-table": PRODUCTS_ID,
          expressions: {
            test: [
              "case",
              [[["is-null", categoryField], categoryField]],
              { default: categoryField },
            ],
          },
          aggregation: [["count"]],
          breakout: [
            ["expression", "test", { "base-type": "type/Text" }],
            [
              "field",
              PRODUCTS.RATING,
              {
                "base-type": "type/Float",
                binning: {
                  strategy: "default",
                },
              },
            ],
          ],
        },
        visualization_settings: {
          "pivot_table.column_split": {
            rows: ["test", "RATING"],
            columns: [],
            values: ["count"],
          },
          "pivot_table.collapsed_rows": {
            value: ['["Doohickey"]', '["Gadget"]', '["Gizmo"]', '["Widget"]'],
            rows: ["test", "RATING"],
          },
        },
      },
      { visitQuestion: true },
    );

    getPivotTableBodyCell(0).should("have.text", "42");
    getPivotTableBodyCell(1).should("have.text", "53");
    getPivotTableBodyCell(2).should("have.text", "51");
    getPivotTableBodyCell(3).should("have.text", "54");
    getPivotTableBodyCell(4).should("have.text", "200");
  });
});

const testQuery = {
  type: "query",
  query: {
    "source-table": ORDERS_ID,
    aggregation: [["count"]],
    breakout: [
      [
        "field",
        PEOPLE.SOURCE,
        { "base-type": "type/Text", "source-field": ORDERS.USER_ID },
      ],
      [
        "field",
        PRODUCTS.CATEGORY,
        { "base-type": "type/Text", "source-field": ORDERS.PRODUCT_ID },
      ],
    ],
  },
  database: SAMPLE_DB_ID,
};

function createTestQuestion({
  display = "pivot",
  visitQuestion = true,
  wrapId = false,
} = {}) {
  const { query } = testQuery;
  const questionDetails = { name: QUESTION_NAME, query, display };

  return H.createQuestion(questionDetails, { visitQuestion, wrapId });
}

function assertOnPivotSettings() {
  cy.findAllByTestId(/draggable-item/).as("fieldOption");

  cy.log("Implicit side-bar assertions");

  cy.findAllByTestId("pivot-table-setting").eq(0);
  cy.get("@fieldOption")
    .eq(0)
    .contains(/Users? → Source/);
  cy.findAllByTestId("pivot-table-setting").eq(1);
  cy.get("@fieldOption")
    .eq(1)
    .contains(/Products? → Category/);
  cy.findAllByTestId("pivot-table-setting").eq(2);
  cy.get("@fieldOption").eq(2).contains("Count");
}

function assertOnPivotFields() {
  cy.log("Implicit assertions on a table itself");

  cy.findByText(/Users? → Source/);
  cy.findByText(/Row totals/i);
  cy.findByText(/Grand totals/i);
  cy.findByText("3,520");
  cy.findByText("4,784");
  cy.findByText("18,760");
}

function openColumnSettings(columnName) {
  H.sidebar()
    .findByTestId(`draggable-item-${columnName}`)
    .icon("ellipsis")
    .click({ force: true });
}

/**
 * @param {string} column
 * @param {("ascending"|"descending")} direction
 */
function sortColumnResults(column, direction) {
  const iconName = direction === "ascending" ? "arrow_up" : "arrow_down";

  cy.findByTestId("sidebar-content")
    .findByTestId(`${column}-settings-button`)
    .click();

  H.popover().icon(iconName).click();
  // Click anywhere to dismiss the popover from UI
  cy.get("body").click("topLeft");

  cy.location("hash").should((hash) => {
    expect(b64hash_to_utf8(hash)).to.include(
      `"pivot_table.column_sort_order":"${direction}"`,
    );
  });
}

function getCellWidth(textEl) {
  return textEl.closest("[data-testid=pivot-table-cell]").width();
}

function getPivotTableBodyCell(index) {
  // eslint-disable-next-line metabase/no-unsafe-element-filtering
  return cy
    .findByLabelText("pivot-table-body-grid")
    .findAllByTestId("pivot-table-cell")
    .eq(index);
}