Skip to content

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

44.3 KB
Raw Blame
const { H } = cy;
import { SAMPLE_DB_ID, WRITABLE_DB_ID } from "e2e/support/cypress_data";
import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";

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

const breakoutBarChart = {
  display: "bar",
  dataset_query: {
    type: "query",
    query: {
      "source-table": ORDERS_ID,
      aggregation: [["count"]],
      breakout: [
        ["field", PEOPLE.SOURCE, { "source-field": ORDERS.USER_ID }],
        ["field", PRODUCTS.CATEGORY, { "source-field": ORDERS.PRODUCT_ID }],
      ],
    },
    database: SAMPLE_DB_ID,
  },
};

describe("scenarios > visualizations > bar chart", () => {
  beforeEach(() => {
    H.restore();
    cy.signInAsNormalUser();
    cy.intercept("POST", "/api/dataset").as("dataset");
  });

  describe("with numeric dimension", () => {
    const query = `
      select null as "a", 10 as "b" union all
      select 5 as "a", 2 as "b" union all
      select 0 as "a", 1 as "b"
    `;

    function getQuestion(visualizationSettings) {
      return {
        dataset_query: {
          type: "native",
          native: { query, "template-tags": {} },
          database: SAMPLE_DB_ID,
        },
        display: "bar",
        visualization_settings: visualizationSettings,
      };
    }

    it("should not show a bar for null values (metabase#12138)", () => {
      H.visitQuestionAdhoc(
        getQuestion({
          "graph.dimensions": ["a"],
          "graph.metrics": ["b"],
        }),
      );

      H.chartPathWithFillColor("#A989C5").should("have.length", 2);
      H.echartsContainer().findByText("(empty)").should("not.exist");
    });

    it("should show an (empty) bar for null values when X axis is ordinal (metabase#12138)", () => {
      H.visitQuestionAdhoc(
        getQuestion({
          "graph.dimensions": ["a"],
          "graph.metrics": ["b"],
          "graph.x_axis.scale": "ordinal",
        }),
      );

      // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
      cy.findByText("(empty)");
    });

    it("should not freeze when opening a timeseries chart with sparse data and without the X-axis (metabase#18776)", () => {
      const questionDetails = {
        dataset_query: {
          type: "native",
          native: {
            query: `
  select 101002 as "id", 1 as "rate"
  union all select 103017, 2
  union all select 210002, 3`,
          },
          database: SAMPLE_DB_ID,
        },
        display: "bar",
        visualization_settings: {
          "graph.dimensions": ["id"],
          "graph.metrics": ["rate"],
          "graph.x_axis.axis_enabled": false,
        },
      };

      H.visitQuestionAdhoc(questionDetails);
      H.chartPathWithFillColor("#509EE3").should("have.length", 3);
    });
  });

  describe("with binned dimension (histogram)", () => {
    it("should filter out null values (metabase#16049)", () => {
      H.visitQuestionAdhoc({
        dataset_query: {
          type: "query",
          query: {
            "source-table": ORDERS_ID,
            aggregation: [["count"]],
            breakout: [
              ["field", ORDERS.DISCOUNT, { binning: { strategy: "default" } }],
            ],
          },
          database: SAMPLE_DB_ID,
        },
      });

      H.chartPathWithFillColor("#509EE3").should("have.length", 5); // there are six bars when null isn't filtered
      // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
      cy.findByText("1,800"); // correct data has this on the y-axis
      // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
      cy.findByText("16,000").should("not.exist"); // If nulls are included the y-axis stretches much higher
    });

    it("should display bar chart for binned column distribution after applying filter (metabase#10493)", () => {
      H.visitQuestionAdhoc({
        dataset_query: {
          type: "query",
          query: {
            "source-table": ORDERS_ID,
          },
          database: SAMPLE_DB_ID,
        },
      });

      cy.log("Click on Quantity column header and select Distribution");
      H.tableHeaderClick("Quantity");
      H.popover().findByText("Distribution").click();
      cy.wait("@dataset");

      cy.log("Verify bar chart is displayed with binned quantity as dimension");
      cy.findByTestId("visualization-root").should(
        "have.attr",
        "data-viz-ui-name",
        "Bar",
      );
      H.chartPathWithFillColor("#509EE3").should("have.length", 9);

      cy.log("Apply filter: count >= 20");
      cy.findByTestId("qb-header-action-panel").findByText("Filter").click();
      H.popover().within(() => {
        cy.findByText("Summaries").click();
        cy.findByText("Count").click();
      });
      H.selectFilterOperator("Greater than or equal to");
      H.popover().within(() => {
        cy.findByPlaceholderText("Enter a number").type("20");
        cy.button("Apply filter").click();
      });

      cy.wait("@dataset");

      cy.log(
        "Verify bar chart is still displayed (binned column should still be treated as dimension)",
      );
      H.assertQueryBuilderRowCount(5);
      cy.findByTestId("visualization-placeholder").should("not.exist");
      cy.findByTestId("visualization-root").should(
        "have.attr",
        "data-viz-ui-name",
        "Bar",
      );
      H.chartPathWithFillColor("#509EE3").should("have.length", 5);
    });
  });

  describe("with very low and high values", () => {
    it("should display correct data values", () => {
      H.visitQuestionAdhoc({
        display: "bar",
        dataset_query: {
          type: "native",
          native: {
            query:
              "select '2027-01-01' as x_axis_1, 'A' as x_axis_2, 20000000 as y_axis\n" +
              "union all\n" +
              "select '2027-01-02' as x_axis_1, 'A' as x_axis_2, 19 as y_axis\n" +
              "union all\n" +
              "select '2027-01-03' as x_axis_1, 'A' as x_axis_2, 20000000 as y_axis\n",
          },
          database: SAMPLE_DB_ID,
        },
        visualization_settings: {
          "graph.show_values": true,
          "graph.dimensions": ["X_AXIS_1", "X_AXIS_2"],
          "graph.metrics": ["Y_AXIS"],
        },
      });

      H.getValueLabels().should("contain", "19").and("contain", "20.0M");
    });
  });

  describe("with x-axis series", () => {
    beforeEach(() => {
      H.visitQuestionAdhoc(breakoutBarChart);

      H.openVizSettingsSidebar();
      H.sidebar().findByText("Data").click();
    });

    it("should allow you to show/hide and reorder columns, and handle filtered and re-added items", () => {
      cy.log("Move Doohickey to the third position");
      H.getDraggableElements().eq(0).as("dragElement");
      H.moveDnDKitElementByAlias("@dragElement", {
        vertical: 100,
        useMouseEvents: true,
      });

      cy.findAllByTestId("legend-item").eq(0).should("contain.text", "Gadget");
      cy.findAllByTestId("legend-item").eq(1).should("contain.text", "Gizmo");
      cy.findAllByTestId("legend-item")
        .eq(2)
        .should("contain.text", "Doohickey");
      cy.findAllByTestId("legend-item").eq(3).should("contain.text", "Widget");

      cy.log("Hide Gizmo");
      H.getDraggableElements().eq(1).icon("close").click({ force: true });

      cy.findByTestId("query-visualization-root")
        .findByText("Gizmo")
        .should("not.exist");
      cy.findAllByTestId("legend-item").should("have.length", 3);
      H.chartPathWithFillColor("#F2A86F").should("be.visible");
      H.chartPathWithFillColor("#F9D45C").should("be.visible");
      H.chartPathWithFillColor("#88BF4D").should("be.visible");

      cy.log("Add Gizmo again");
      H.leftSidebar().button("Add another series").click();
      H.popover().findByText("Gizmo").click();

      cy.findByTestId("query-visualization-root")
        .findByText("Gizmo")
        .should("exist");
      cy.findAllByTestId("legend-item").should("have.length", 4);
      H.chartPathWithFillColor("#F2A86F").should("be.visible");
      H.chartPathWithFillColor("#F9D45C").should("be.visible");
      H.chartPathWithFillColor("#88BF4D").should("be.visible");
      H.chartPathWithFillColor("#A989C5").should("be.visible");

      cy.log("Hide Gizmo again");
      H.getDraggableElements().eq(1).should("have.text", "Gizmo");
      H.getDraggableElements().eq(1).icon("close").click({ force: true });

      cy.log("Filter out Gadget");
      H.queryBuilderHeader()
        .button(/Filter/)
        .click();
      H.popover().within(() => {
        cy.findByText("Product").click();
        cy.findByText("Category").click();
      });
      H.selectFilterOperator("Is not");
      H.popover().within(() => {
        cy.findByText("Gadget").click();
        cy.button("Apply filter").click();
      });
      H.getDraggableElements().should("have.length", 2);
      H.getDraggableElements().eq(0).should("have.text", "Doohickey");
      H.getDraggableElements().eq(1).should("have.text", "Widget");

      cy.log("Remove the filter");
      cy.findByTestId("qb-filters-panel").icon("close").click();

      H.getDraggableElements().should("have.length", 3);
      H.getDraggableElements().eq(0).should("have.text", "Gadget");
      H.getDraggableElements().eq(1).should("have.text", "Doohickey");
      H.getDraggableElements().eq(2).should("have.text", "Widget");

      cy.log("Add Gizmo to the end of the list");
      H.leftSidebar().button("Add another series").click();
      H.popover().findByText("Gizmo").click();

      H.getDraggableElements().should("have.length", 4);
      H.getDraggableElements().eq(0).should("have.text", "Gadget");
      H.getDraggableElements().eq(1).should("have.text", "Gizmo");
      H.getDraggableElements().eq(2).should("have.text", "Doohickey");
      H.getDraggableElements().eq(3).should("have.text", "Widget");

      cy.log("Drill through a legend item");
      cy.findAllByTestId("legend-item").contains("Gadget").click();
      H.popover().findByText("See these Orders").click();
      cy.findByTestId("qb-filters-panel")
        .findByText("Product → Category is Gadget")
        .should("exist");
    });
  });

  // Note (EmmadUsmani): see `line_chart.cy.spec.js` for more test cases of this
  describe("with split y-axis (metabase#12939)", () => {
    it("should split the y-axis when column settings differ", () => {
      H.visitQuestionAdhoc({
        dataset_query: {
          type: "query",
          query: {
            "source-table": ORDERS_ID,
            aggregation: [
              ["avg", ["field", ORDERS.TOTAL, null]],
              ["min", ["field", ORDERS.TOTAL, null]],
            ],
            breakout: [
              ["field", ORDERS.CREATED_AT, { "temporal-unit": "month" }],
            ],
          },
          database: SAMPLE_DB_ID,
        },
        display: "bar",
        visualization_settings: {
          column_settings: {
            '["name","avg"]': { number_style: "decimal" },
            '["name","min"]': { number_style: "percent" },
          },
        },
      });

      H.echartsContainer().within(() => {
        cy.get("text").contains("Average of Total").should("be.visible");
        cy.get("text").contains("Min of Total").should("be.visible");
      });
    });

    it("should not split the y-axis when semantic_type, column settings are same and values are not far", () => {
      H.visitQuestionAdhoc({
        dataset_query: {
          type: "query",
          query: {
            "source-table": ORDERS_ID,
            aggregation: [
              ["avg", ["field", ORDERS.TOTAL, null]],
              ["min", ["field", ORDERS.TOTAL, null]],
            ],
            breakout: [
              ["field", ORDERS.CREATED_AT, { "temporal-unit": "month" }],
            ],
          },
          database: SAMPLE_DB_ID,
        },
        display: "bar",
      });

      H.echartsContainer().within(() => {
        cy.findByText("Created At: Month").should("be.visible");
        cy.findByText("Average of Total").should("not.exist");
        cy.findByText("Min of Total").should("not.exist");
      });
    });

    it("should split the y-axis on native queries with two numeric columns", () => {
      H.visitQuestionAdhoc({
        display: "bar",
        dataset_query: {
          type: "native",
          native: {
            query:
              'SELECT products.category AS "x", COUNT(*) AS "m1", AVG(orders.discount) AS "m2" ' +
              "FROM orders " +
              "JOIN products ON orders.product_id = products.id " +
              "GROUP BY products.category",
          },
          database: SAMPLE_DB_ID,
        },
        visualization_settings: {
          "graph.dimensions": ["x"],
          "graph.metrics": ["m1", "m2"],
        },
      });

      H.echartsContainer().within(() => {
        cy.get("text").contains("m1").should("exist");
        cy.get("text").contains("m2").should("exist");
      });
    });

    it("when two axis should show only one related to the hovered series (metabase#49874, metabase#48847)", () => {
      const question = {
        dataset_query: {
          type: "query",
          query: {
            "source-table": ORDERS_ID,
            aggregation: [
              ["sum", ["field", ORDERS.QUANTITY, null]],
              ["sum", ["field", ORDERS.TOTAL, null]],
            ],
            breakout: [
              ["field", ORDERS.CREATED_AT, { "temporal-unit": "month" }],
            ],
          },
          database: 1,
        },
        display: "bar",
      };

      H.visitQuestionAdhoc(question);

      H.echartsContainer().within(() => {
        cy.findByText("Sum of Quantity").should("be.visible");
        cy.findByText("Sum of Total").should("be.visible");
      });

      H.chartGridLines().should("exist");

      H.chartPathWithFillColor("#88BF4D").first().realHover();

      H.echartsContainer().within(() => {
        cy.findByText("Sum of Quantity").should("be.visible");
        cy.findByText("Sum of Total").should("not.exist");
      });
      H.chartGridLines().should("exist");

      H.chartPathWithFillColor("#98D9D9").first().realHover();

      H.echartsContainer().within(() => {
        cy.findByText("Sum of Quantity").should("not.exist");
        cy.findByText("Sum of Total").should("be.visible");
      });
      H.chartGridLines().should("exist");
    });
  });

  describe("with stacked bars", () => {
    [false, true].forEach((devMode) => {
      it(`should drill-through correctly when stacking - development-mode: ${devMode}`, () => {
        cy.intercept("/api/session/properties", (req) => {
          req.continue((res) => {
            res.body["token-features"].development_mode = devMode;
          });
        });
        H.visitQuestionAdhoc({
          dataset_query: {
            database: SAMPLE_DB_ID,
            type: "query",
            query: {
              "source-table": PRODUCTS_ID,
              aggregation: [["count"]],
              breakout: [
                ["field", PRODUCTS.CATEGORY],
                ["field", PRODUCTS.CREATED_AT, { "temporal-unit": "month" }],
              ],
            },
          },
          display: "bar",
          visualization_settings: { "stackable.stack_type": "stacked" },
        });

        cy.findAllByTestId("legend-item")
          .findByText("Doohickey")
          .should("be.visible");
        cy.findByTestId("development-watermark").should(
          devMode ? "exist" : "not.exist",
        );

        cy.findAllByTestId("legend-item").findByText("Doohickey").click();
        // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
        cy.findByText("See these Products").click();

        // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
        cy.findByText("Category is Doohickey").should("be.visible");
      });
    });

    it("should not crash when renaming an aggregation changes sibling column deduplication (metabase#68819)", () => {
      // Create a question with two Sum of Total aggregations
      // These will be deduplicated as "sum" and "sum_2"
      const questionDetails = {
        display: "bar",
        query: {
          "source-table": ORDERS_ID,
          aggregation: [
            ["sum", ["field", ORDERS.TOTAL, null]],
            ["sum", ["field", ORDERS.TOTAL, null]],
          ],
          breakout: [
            ["field", ORDERS.CREATED_AT, { "temporal-unit": "month" }],
            ["field", PRODUCTS.CATEGORY, { "source-field": ORDERS.PRODUCT_ID }],
          ],
        },
        visualization_settings: {
          "stackable.stack_type": "stacked",
          "graph.dimensions": ["CREATED_AT", "CATEGORY"],
          "graph.metrics": ["sum", "sum_2"],
        },
      };

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

      H.echartsContainer().should("be.visible");

      H.openNotebook();

      H.getNotebookStep("summarize")
        .findByTestId("aggregate-step")
        .findAllByTestId("notebook-cell-item")
        .first()
        .click();

      cy.findByLabelText("Back").click();

      H.popover().findByText("Custom Expression").click();

      H.CustomExpressionEditor.nameInput().clear().type("Sum");
      H.popover().button("Update").click();

      H.saveSavedQuestion();

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

      // The bug would cause: TypeError: cannot read properties of undefined (reading 'name')
      H.echartsContainer().should("be.visible");
      cy.findByTestId("query-builder-main")
        .findByText(/error/i)
        .should("not.exist");

      cy.reload();
      H.echartsContainer().should("be.visible");
    });
  });

  it("supports gray series colors", () => {
    const grayColor = "#F2F2F3";

    H.visitQuestionAdhoc({
      ...breakoutBarChart,
      visualization_settings: {
        "graph.dimensions": ["CATEGORY", "SOURCE"],
        "graph.metrics": ["count"],
      },
    });

    // Ensure the gray color did not get assigned to series
    H.chartPathWithFillColor("#88BF4D").should("be.visible");
    H.chartPathWithFillColor(grayColor).should("not.exist");

    H.openVizSettingsSidebar();

    // Open color picker for the first series
    cy.findByLabelText("#88BF4D").click();

    // Assign gray color to the first series
    cy.findByLabelText(grayColor).click();

    H.chartPathWithFillColor(grayColor).should("be.visible");
  });

  it("supports up to 100 series (metabase#28796)", () => {
    H.visitQuestionAdhoc({
      display: "bar",
      dataset_query: {
        database: SAMPLE_DB_ID,
        type: "query",
        query: {
          "source-table": ORDERS_ID,
          aggregation: [["count"]],
          filter: ["and", ["<", ["field", ORDERS.ID, null], 101]],
          breakout: [
            ["field", ORDERS.CREATED_AT, { "temporal-unit": "year" }],
            ["field", ORDERS.ID],
          ],
        },
      },
      visualization_settings: {
        "graph.dimensions": ["CREATED_AT", "SUBTOTAL"],
        "graph.metrics": ["count"],
      },
    });

    H.openVizSettingsSidebar();
    H.leftSidebar().button("90 more series").click();
    cy.get("[data-testid^=draggable-item]").should("have.length", 100);

    cy.findByTestId("qb-filters-panel")
      .findByText("ID is less than 101")
      .click();
    H.popover().within(() => {
      cy.findByDisplayValue("101").type("{backspace}2");
      cy.button("Update filter").click();
    });

    H.queryBuilderMain().findByText(
      "This chart type doesn't support more than 100 series of data.",
    );
    cy.get("[data-testid^=draggable-item]").should("have.length", 0);
  });

  it("should support showing data points with > 10 series (#33725)", () => {
    cy.signInAsAdmin();
    const stateFilter = [
      "=",
      ["field", PEOPLE.STATE, {}],
      "AK",
      "AL",
      "AR",
      "AZ",
      "CA",
      "CO",
      "CT",
      "FL",
      "GA",
      "IA",
    ];

    const dateFilter = [
      "between",
      [
        "field",
        ORDERS.CREATED_AT,
        {
          "base-type": "type/DateTime",
        },
      ],
      "2026-09-01",
      "2026-09-30",
    ];

    const avgTotalByMonth = {
      name: "Average Total by Month",
      type: "query",
      query: {
        "source-table": ORDERS_ID,
        aggregation: [["avg", ["field", ORDERS.TOTAL]]],
        breakout: [["field", ORDERS.CREATED_AT, { "temporal-unit": "month" }]],
      },
      display: "line",
    };

    const sumTotalByMonth = {
      name: "Sum Total by Month",
      type: "query",
      query: {
        "source-table": ORDERS_ID,
        aggregation: [["sum", ["field", ORDERS.TOTAL]]],
        breakout: [["field", ORDERS.CREATED_AT, { "temporal-unit": "month" }]],
      },
      display: "line",
    };

    const multiMetric = {
      name: "Should split",
      type: "query",
      query: {
        "source-table": ORDERS_ID,
        aggregation: [
          ["avg", ["field", ORDERS.TAX]],
          ["sum", ["field", ORDERS.TAX]],
          ["min", ["field", ORDERS.TAX]],
          ["max", ["field", ORDERS.TAX]],
          ["avg", ["field", ORDERS.SUBTOTAL]],
          ["sum", ["field", ORDERS.SUBTOTAL]],
          ["min", ["field", ORDERS.SUBTOTAL]],
          ["max", ["field", ORDERS.SUBTOTAL]],
          ["avg", ["field", ORDERS.TOTAL]],
          ["sum", ["field", ORDERS.TOTAL]],
          ["min", ["field", ORDERS.TOTAL]],
          ["max", ["field", ORDERS.TOTAL]],
        ],
        breakout: [["field", ORDERS.CREATED_AT, { "temporal-unit": "month" }]],
        filter: dateFilter,
      },
      display: "bar",
      visualization_settings: {
        "graph.show_values": true,
      },
    };

    const breakoutQuestion = {
      name: "Should not Split",
      type: "query",
      query: {
        "source-table": ORDERS_ID,
        aggregation: [["count"]],
        breakout: [
          ["field", ORDERS.CREATED_AT, { "temporal-unit": "month" }],
          ["field", PEOPLE.STATE, { "source-field": ORDERS.USER_ID }],
        ],
        filter: ["and", stateFilter, dateFilter],
      },
      display: "bar",
      visualization_settings: {
        "graph.dimensions": ["CREATED_AT", "STATE"],
        "graph.metrics": ["count"],
        "graph.show_values": true,
      },
    };

    H.createDashboardWithQuestions({
      dashboardName: "Split Test Dashboard",
      questions: [multiMetric],
    }).then(({ dashboard }) => {
      H.createQuestion(sumTotalByMonth, { wrapId: true }).then(() => {
        cy.get("@questionId").then((questionId) => {
          H.cypressWaitAll([
            H.createQuestionAndAddToDashboard(avgTotalByMonth, dashboard.id, {
              series: [
                {
                  id: questionId,
                },
              ],
              col: 12,
              row: 0,
              visualization_settings: {
                "card.title": "Multi Series",
              },
            }),
            H.createQuestionAndAddToDashboard(breakoutQuestion, dashboard.id, {
              col: 0,
              row: 9,
              size_x: 20,
            }),
          ]).then(() => {
            H.visitDashboard(dashboard.id);
          });
        });
      });
    });

    //This card is testing #33725 now, as the changes made for #34618 would cause "Should not Split" to no longer split and error
    cy.findAllByTestId("dashcard")
      .contains("[data-testid=dashcard]", "Should split")
      .within(() => {
        // Verify this axis tick exists twice which verifies there are two y-axes
        H.echartsContainer()
          .findAllByText("21.0k")
          .should("have.length", 2)
          .and("be.visible");
      });

    cy.findAllByTestId("dashcard")
      .contains("[data-testid=dashcard]", "Multi Series")
      .within(() => {
        H.echartsContainer().findByText("Average Total by Month");
        H.echartsContainer().findByText("Sum Total by Month");
      });

    cy.log("Should not produce a split axis graph (#34618)");
    cy.findAllByTestId("dashcard")
      .contains("[data-testid=dashcard]", "Should not Split")
      .within(() => {
        H.getValueLabels()
          .should("contain", "6")
          .and("contain", "13")
          .and("contain", "19");
        H.echartsContainer().findAllByText("Count").should("have.length", 1);
      });
  });

  it("should correctly handle bar sizes and tool-tips for multiple y-axis metrics with column scaling  (#43536)", () => {
    cy.signInAsAdmin();

    const column_settings = { '["name","sum"]': { scale: 0.5 } };
    const multiMetric = {
      name: "Should split",
      type: "query",
      query: {
        "source-table": ORDERS_ID,
        aggregation: [
          ["sum", ["field", ORDERS.TOTAL]],
          ["sum", ["field", ORDERS.TOTAL]],
        ],
        breakout: [["field", ORDERS.CREATED_AT, { "temporal-unit": "year" }]],
      },
      display: "bar",
      visualization_settings: {
        column_settings,
        "graph.show_values": true,
        "graph.stackable.stack_type": "stacked",
        series_settings: {
          sum_2: {
            axis: "left",
          },
          sum: {
            axis: "left",
          },
        },
      },
    };

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

    const [firstMetric, secondMetric] = H.chartPathsWithFillColors([
      "#88BF4D",
      "#98D9D9",
    ]);
    firstMetric.then(($metricOne) => {
      const { height: heightMetricOne } = $metricOne[0].getBoundingClientRect();
      secondMetric.then(($metricTwo) => {
        const { height: heightMetricTwo } =
          $metricTwo[0].getBoundingClientRect();

        // since the first metric is scaled to be half of the second metric
        // the first bar should be half the size of the first bar
        // within a given tolerance
        expect(heightMetricOne).to.be.closeTo(heightMetricTwo / 2, 0.5);
      });
    });

    H.chartPathWithFillColor("#88BF4D").first().realHover();
    H.assertEChartsTooltip({
      header: "2025",
      rows: [
        {
          color: "#88BF4D",
          name: "Sum of Total",
          value: "21,078.43",
          index: 0,
        },
        {
          color: "#98D9D9",
          name: "Sum of Total",
          value: "42,156.87",
          index: 1,
        },
      ],
    });
  });

  it("should correctly show tool-tips when stacked bar charts contain a negative total or multiple positive and negative segments (#39012, #47596)", () => {
    cy.signInAsAdmin();

    H.createNativeQuestion(
      {
        name: "42948",
        native: {
          query:
            "    SELECT DATE '2024-05-21' AS created_at, 'blue' AS category, -7 as v\nUNION ALL SELECT DATE '2024-05-21' , 'yellow', 5\nUNION ALL SELECT DATE '2024-05-20' , 'blue', -16\nUNION ALL SELECT DATE '2024-05-20' , 'yellow', 8\nUNION ALL SELECT DATE '2024-05-19' ,'blue', 2\nUNION ALL SELECT DATE '2024-05-19' ,'yellow', 8\nUNION ALL SELECT DATE '2024-05-22' ,'blue', 2\nUNION ALL SELECT DATE '2024-05-22' ,'yellow', -2\nUNION ALL SELECT DATE '2024-05-23' ,'blue', 3\nUNION ALL SELECT DATE '2024-05-23' ,'yellow', -2\nORDER BY created_at",
        },

        display: "bar",
        visualization_settings: {
          "graph.dimensions": ["CREATED_AT", "CATEGORY"],
          "graph.metrics": ["V"],
          "stackable.stack_type": "stacked",
        },
      },
      { visitQuestion: true },
    );

    H.chartPathWithFillColor("#A989C5").eq(0).realHover();
    H.assertEChartsTooltip({
      rows: [
        {
          color: "#A989C5",
          name: "blue",
          value: "2",
          secondaryValue: "20.00 %",
        },
        {
          color: "#F9D45C",
          name: "yellow",
          value: "8",
          secondaryValue: "80.00 %",
        },
        {
          name: "Total",
          value: "10",
          secondaryValue: "100 %",
        },
      ],
    });
    H.echartsTriggerBlur();

    H.chartPathWithFillColor("#A989C5").eq(1).realHover();
    H.assertEChartsTooltip({
      rows: [
        {
          color: "#F9D45C",
          name: "yellow",
          value: "8",
          secondaryValue: "100 %",
        },
        { name: "Total positive", value: "8" },
        {
          color: "#A989C5",
          name: "blue",
          value: "-16",
          secondaryValue: "-100 %",
        },
        { name: "Total negative", value: "-16" },
        { name: "Total", value: "-8" },
      ],
    });
    H.echartsTriggerBlur();

    H.chartPathWithFillColor("#A989C5").eq(2).realHover();
    H.assertEChartsTooltip({
      rows: [
        {
          color: "#F9D45C",
          name: "yellow",
          value: "5",
          secondaryValue: "100 %",
        },
        { name: "Total positive", value: "5" },
        {
          color: "#A989C5",
          name: "blue",
          value: "-7",
          secondaryValue: "-100 %",
        },
        { name: "Total negative", value: "-7" },
        { name: "Total", value: "-2" },
      ],
    });
    H.echartsTriggerBlur();

    H.chartPathWithFillColor("#A989C5").eq(3).realHover();
    H.assertEChartsTooltip({
      rows: [
        {
          color: "#A989C5",
          name: "blue",
          value: "2",
          secondaryValue: "100 %",
        },
        { name: "Total positive", value: "2" },
        {
          color: "#F9D45C",
          name: "yellow",
          value: "-2",
          secondaryValue: "-100 %",
        },
        { name: "Total negative", value: "-2" },
        { name: "Total", value: "0" },
      ],
    });
    H.echartsTriggerBlur();

    H.chartPathWithFillColor("#A989C5").eq(4).realHover();
    H.assertEChartsTooltip({
      rows: [
        {
          color: "#A989C5",
          name: "blue",
          value: "3",
          secondaryValue: "100 %",
        },
        { name: "Total positive", value: "3" },
        {
          color: "#F9D45C",
          name: "yellow",
          value: "-2",
          secondaryValue: "-100 %",
        },
        { name: "Total negative", value: "-2" },
        { name: "Total", value: "1" },
      ],
    });
    H.echartsTriggerBlur();

    cy.log("multiple positive and multiple negative segments (#47596)");
    H.createNativeQuestion(
      {
        name: "47596",
        native: {
          query: `${[
            "select date '2024-05-21' AS created_at, 'cat1' AS category, 2 as v",
            "select date '2024-05-21', 'cat2', -1",
            "select date '2024-05-21', 'cat3', 1",
            "select date '2024-05-21', 'cat4', -1",
          ].join(" union all ")} order by created_at`,
        },

        display: "bar",
        visualization_settings: {
          "graph.dimensions": ["CREATED_AT", "CATEGORY"],
          "graph.metrics": ["V"],
          "stackable.stack_type": "stacked",
        },
      },
      { visitQuestion: true },
    );

    H.chartPathWithFillColor("#F9D45C").eq(0).realHover();
    H.assertEChartsTooltip({
      rows: [
        {
          color: "#EF8C8C",
          name: "cat1",
          value: "2",
          secondaryValue: "66.67 %",
        },
        {
          color: "#F2A86F",
          name: "cat3",
          value: "1",
          secondaryValue: "33.33 %",
        },
        { name: "Total positive", value: "3" },
        {
          color: "#98D9D9",
          name: "cat4",
          value: "-1",
          secondaryValue: "-50.00 %",
        },
        {
          color: "#F9D45C",
          name: "cat2",
          value: "-1",
          secondaryValue: "-50.00 %",
        },
        { name: "Total negative", value: "-2" },
        { name: "Total", value: "1" },
      ],
    });
    H.echartsTriggerBlur();
  });

  it("should format goal tooltip value as a percent when the Stacking option is 'Stack - 100%'", () => {
    H.visitQuestionAdhoc({
      ...breakoutBarChart,
      visualization_settings: {
        "graph.goal_value": 87.5,
        "graph.show_goal": true,
        "stackable.stack_type": "normalized",
      },
    });

    H.goalLineMarker().trigger("mousemove");

    H.tooltip().within(() => {
      cy.findByText("Goal:").should("exist");
      cy.findByText("87.5%").should("exist");
    });
  });

  it("should display all axis labels for 12 months of data (metabase#60475)", () => {
    cy.viewport(1600, 800);

    // Create a bar chart showing count of orders by month for the last 12 months
    H.visitQuestionAdhoc({
      display: "bar",
      visualization_settings: {
        "graph.x_axis.axis_enabled": "compact",
      },
      dataset_query: {
        type: "query",
        query: {
          "source-table": ORDERS_ID,
          aggregation: [["count"]],
          breakout: [
            [
              "field",
              ORDERS.CREATED_AT,
              { "base-type": "type/DateTime", "temporal-unit": "month" },
            ],
          ],
          filter: [
            "time-interval",
            ["field", ORDERS.CREATED_AT, { "base-type": "type/DateTime" }],
            -12,
            "month",
          ],
        },
        database: SAMPLE_DB_ID,
      },
    });

    // Wait for the chart to render
    cy.wait("@dataset");
    H.echartsContainer().should("be.visible");

    H.echartsContainer()
      .findAllByText(
        /^(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) \d{4}$/,
      )
      .should("have.length", 12)
      .and("be.visible");
  });

  it("should rotate axis labels when they do not fit horizontally instead of hiding them (metabase#68048)", () => {
    // Use a smaller viewport to ensure labels need to rotate
    cy.viewport(820, 800);

    const query = `
      SELECT * FROM (
        VALUES
        ('Alnyba', 390000),
        ('Bvsieginlri', 500000),
        ('Cflonta', 700000),
        ('Dgamruh', 50000),
        ('Eitstrugb', 130000),
        ('Farnotcs', 107000),
        ('Gkro', 750000)
      ) AS Data(LABEL, amount)
    `;

    H.visitQuestionAdhoc({
      display: "bar",
      dataset_query: {
        type: "native",
        native: { query, "template-tags": {} },
        database: SAMPLE_DB_ID,
      },
      visualization_settings: {
        "graph.dimensions": ["LABEL"],
        "graph.metrics": ["amount"],
      },
    });

    // Open the data reference sidebar to squish the data further
    cy.findByLabelText("Learn about your data").click();

    cy.wait("@dataset");
    H.echartsContainer().should("be.visible");

    // Verify all 7 labels are visible and rotated (not hidden)
    const expectedLabels = [
      "Alnyba",
      "Bvsieginlri",
      "Cflonta",
      "Dgamruh",
      "Eitstrugb",
      "Farnotcs",
      "Gkro",
    ];

    H.echartsContainer().within(() => {
      // When labels don't fit horizontally, ECharts rotates them
      // Rotated labels have a transform attribute containing rotation
      expectedLabels.forEach((label) => {
        cy.contains("text", label).should("be.visible");
      });

      // Verify labels are rotated by checking for transform attribute with rotation
      // ECharts applies rotation via transform attribute when labels don't fit
      cy.get("text")
        .filter((_, el) =>
          expectedLabels.some((label) => el.textContent?.includes(label)),
        )
        .should("have.length", 7)
        .first()
        .should("have.attr", "transform")
        .and("match", /matrix/);
    });
  });

  it("should allow selecting breakout dimension before metrics (metabase#49529)", () => {
    const question = {
      dataset_query: {
        type: "query",
        query: {
          "source-table": ORDERS_ID,
        },
        database: 1,
      },
      display: "bar",
    };

    H.visitQuestionAdhoc(question);

    H.openVizSettingsSidebar();

    cy.findAllByTestId("chart-setting-select").eq(0).click();
    H.popover().findByText("ID").click();

    H.leftSidebar().findByText("Add series breakout").click();
    H.popover().findByText("Quantity").click();

    H.leftSidebar().within(() => {
      cy.findByText("Y-axis");
      cy.findByText("Nothing to order");
    });
  });

  it("should handle invalid x-axis scale (metabase#25156)", () => {
    const questionDetails = {
      name: "25156",
      query: {
        "source-table": REVIEWS_ID,
        aggregation: [["count"]],
        breakout: [
          ["field", REVIEWS.CREATED_AT, { "temporal-unit": "year" }],
          ["field", REVIEWS.RATING, null],
        ],
      },
      display: "bar",
      visualization_settings: {
        "graph.dimensions": ["CREATED_AT", "RATING"],
        "graph.metrics": ["count"],
        "graph.x_axis.scale": "linear",
      },
    };

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

    H.echartsContainer()
      .should("contain", "2025")
      .and("contain", "2026")
      .and("contain", "2027")
      .and("contain", "2028");
  });

  it("should reflect/apply sorting to the x-axis (metabase#27279)", () => {
    const questionDetails = {
      name: "27279",
      native: {
        query:
          "select -3 o, 'F2021' k, 1 v\nunion all select -2, 'V2021', 2\nunion all select -1, 'S2022', 3\nunion all select 0, 'F2022', 4",
        "template-tags": {},
      },
    };

    H.createNativeQuestion(questionDetails).then(({ body: { id } }) => {
      H.visitQuestionAdhoc({
        dataset_query: {
          type: "query",
          query: {
            "source-table": `card__${id}`,
            aggregation: [
              ["sum", ["field", "V", { "base-type": "type/Integer" }]],
            ],
            breakout: [
              ["field", "K", { "base-type": "type/Text" }],
              ["field", "O", { "base-type": "type/Integer" }],
            ],
            "order-by": [
              ["asc", ["field", "O", { "base-type": "type/Integer" }]],
            ],
          },
          database: SAMPLE_DB_ID,
        },
        display: "bar",
        visualization_settings: {
          "graph.dimensions": ["K", "O"],
          "graph.metrics": ["sum"],
        },
      });
    });

    const legendItems = ["-3", "-2", "-1", "0"];
    compareValuesInOrder(cy.findAllByTestId("legend-item"), legendItems);

    // ECharts pads the tick labels with spaces, so trim them before the comparison
    H.echartsContainer()
      .find("text")
      .filter((_, el) =>
        /^(F2021|V2021|S2022|F2022)$/.test(el.textContent.trim()),
      )
      .should(($ticks) => {
        expect(
          $ticks.toArray().map((el) => el.textContent.trim()),
        ).to.deep.equal(["F2021", "V2021", "S2022", "F2022"]);
      });

    // Extra step, just to be overly cautious
    H.chartPathWithFillColor("#98D9D9").realHover();

    H.assertEChartsTooltip({
      header: "F2021",
      rows: [
        {
          color: "#98D9D9",
          name: "-3",
          value: "1",
        },
        {
          color: "#F2A86F",
          name: "-2",
          value: "(empty)",
        },
        {
          color: "#F9D45C",
          name: "-1",
          value: "(empty)",
        },
        {
          color: "#509EE3",
          name: "0",
          value: "(empty)",
        },
      ],
    });

    H.chartPathWithFillColor("#509EE3").realHover();
    H.assertEChartsTooltip({
      header: "F2022",
      rows: [
        {
          color: "#98D9D9",
          name: "-3",
          value: "(empty)",
        },
        {
          color: "#F2A86F",
          name: "-2",
          value: "(empty)",
        },
        {
          color: "#F9D45C",
          name: "-1",
          value: "(empty)",
        },
        {
          color: "#509EE3",
          name: "0",
          value: "4",
        },
      ],
    });
  });

  describe("issue 20548", () => {
    const questionDetails = {
      name: "20548",
      query: {
        "source-table": PRODUCTS_ID,
        aggregation: [["sum", ["field", PRODUCTS.PRICE, null]], ["count"]],
        breakout: [["field", PRODUCTS.CATEGORY, null]],
      },
      display: "bar",
      // We are reversing the order of metrics via API
      visualization_settings: {
        "graph.metrics": ["count", "sum"],
        "graph.dimensions": ["CATEGORY"],
      },
    };

    function removeAggregationItem(item) {
      cy.findAllByTestId("aggregation-item")
        .contains(item)
        .siblings(".Icon-close")
        .click();

      cy.wait("@dataset");
    }

    function addAggregationItem(item) {
      cy.findByTestId("add-aggregation-button").click();
      H.popover().contains(item).click();

      cy.wait("@dataset");
    }

    /**
     * @param {string} item
     * @param {number} frequency
     */
    function assertOnLegendItemFrequency(item, frequency) {
      cy.findAllByTestId("legend-item")
        .filter(`:contains("${item}")`)
        .should("have.length", frequency);
    }

    beforeEach(() => {
      H.createQuestion(questionDetails, { visitQuestion: true });
      H.summarize();
    });

    it("should not display duplicate Y-axis after modifying/reordering metrics (metabase#20548)", () => {
      removeAggregationItem("Count");
      // Ensure bars of only one series exist
      H.chartPathWithFillColor("#88BF4D").should("have.length", 4);
      H.chartPathWithFillColor("#509EE3").should("not.exist");

      addAggregationItem("Count");
      // Ensure bars of two series exist
      H.chartPathWithFillColor("#88BF4D").should("have.length", 4);
      H.chartPathWithFillColor("#509EE3").should("have.length", 4);

      // Although the test already fails on the previous step, let's add some more assertions to prevent future regressions
      assertOnLegendItemFrequency("Count", 1);
      assertOnLegendItemFrequency("Sum of Price", 1);

      H.openVizSettingsSidebar();
      H.sidebar().findByDisplayValue("Count").should("be.visible");
    });
  });

  describe("issue 63671", () => {
    beforeEach(() => {
      H.createQuestion(
        {
          query: {
            "source-table": PRODUCTS_ID,
            aggregation: [["count"]],
            breakout: [
              [
                "field",
                PRODUCTS.CREATED_AT,
                {
                  "temporal-unit": "year",
                },
              ],
            ],
            filter: [
              "between",
              ["field", PRODUCTS.CREATED_AT, null],
              "2028-01-01",
              "2028-12-31",
            ],
          },
          display: "bar",
        },
        { visitQuestion: true },
      );
    });

    it("should not show an extra value on bar charts when there is only value on the x axis (metabase#63671)", () => {
      cy.findByTestId("query-visualization-root").findByText("2028");
    });
  });
});

function compareValuesInOrder(selector, values) {
  selector.each(($item, index) => {
    cy.wrap($item).invoke("text").should("eq", values[index]);
  });
}

describe("scenarios > visualizations > bar chart > issue 55853", () => {
  const questionDetails = {
    name: "55853",
    database: WRITABLE_DB_ID,
    native: {
      query: `select 'Category A' as category, 0.0001 as value union all
      select 'Category B' as category, 0.0002 as value union all
      select 'Category C' as category, 0.00015 as value union all
      select 'Category D' as category, 0.00025 as value`,
      "template-tags": {},
    },
    display: "bar",
    visualization_settings: {
      "graph.dimensions": ["category"],
      "graph.metrics": ["value"],
      column_settings: {
        '["name","value"]': {
          number_style: "percent",
        },
      },
    },
  };

  beforeEach(() => {
    H.restore("postgres-12");
    cy.signInAsAdmin();
  });

  it("should not have y-axis labels colliding with very low percentages (metabase#55853)", () => {
    H.createNativeQuestion(questionDetails, { visitQuestion: true });

    cy.log("Verify that the chart renders successfully");
    H.echartsContainer().should("be.visible");
    H.echartsContainer().find("text").should("contain", "%");
    H.chartPathWithFillColor("#88BF4D").should("have.length", 4);

    cy.log("Check that axis labels and title don't overlap");
    H.echartsContainer()
      .find("text")
      .then(($texts) => {
        const texts = $texts.toArray();
        const axisTitle = texts.find(
          (el) => el.textContent?.trim() === "value",
        );
        const percentLabels = texts.filter((el) =>
          el.textContent?.includes("%"),
        );

        expect(axisTitle, "y-axis title").to.exist;
        expect(percentLabels).to.have.length.greaterThan(0);

        const titleRight = axisTitle.getBoundingClientRect().right;
        percentLabels.forEach((el) => {
          expect(
            el.getBoundingClientRect().left - titleRight,
            `Label "${el.textContent}" should not overlap with the axis title`,
          ).to.be.greaterThan(5);
        });
      });

    cy.log(
      "Verify tooltips show correct percentage values (not incorrectly rounded)",
    );
    H.chartPathWithFillColor("#88BF4D").first().realHover();
    H.assertEChartsTooltip({
      header: "Category A",
      rows: [
        {
          name: "value",
          value: "0.01%",
        },
      ],
    });
  });
});