Skip to content

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

33.6 KB
Raw Blame
const { H } = cy;
import { dedent } from "ts-dedent";

import { SAMPLE_DB_ID, WRITABLE_DB_ID } from "e2e/support/cypress_data";
import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";

const { PRODUCTS, PRODUCTS_ID, ORDERS, ORDERS_ID } = SAMPLE_DATABASE;

describe("issue 13751", { tags: "@external" }, () => {
  const CC_NAME = "C-States";
  const PG_DB_NAME = "QA Postgres12";

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

    H.startNewQuestion();
    H.miniPicker().within(() => {
      cy.findByText(PG_DB_NAME).should("be.visible").click();
      cy.findByTextEnsureVisible("People").click();
    });
  });

  it("should allow using strings in filter based on a custom column (metabase#13751)", () => {
    H.addCustomColumn();
    H.enterCustomColumnDetails({
      formula: 'regexExtract([State], "^C[A-Z]")',
      name: CC_NAME,
    });
    cy.button("Done").should("not.be.disabled").click();

    H.getNotebookStep("filter")
      .findByText(/Add filter/)
      .click();
    H.popover().findByText(CC_NAME).click();
    H.selectFilterOperator("Is");
    H.popover().within(() => {
      cy.findByPlaceholderText("Enter some text").type("CO");
      cy.button("Add filter").click();
    });

    H.visualize();

    H.queryBuilderMain().findByText("Arnold Adams").should("be.visible");
  });
});

describe("postgres > question > custom columns", { tags: "@external" }, () => {
  beforeEach(() => {
    H.restore("postgres-12");
    cy.signInAsAdmin();

    cy.request(`/api/database/${WRITABLE_DB_ID}/schema/public`).then(
      ({ body }) => {
        const tableId = body.find((table) => table.name === "orders").id;
        H.openTable({
          database: WRITABLE_DB_ID,
          table: tableId,
          mode: "notebook",
        });
      },
    );

    cy.findByRole("button", { name: "Summarize" }).click();
  });

  it("`Percentile` custom expression function should accept two parameters (metabase#15714)", () => {
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("Pick a function or metric").click();
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("Custom Expression").click();
    H.enterCustomColumnDetails({
      formula: "Percentile([Subtotal], 0.1)",
      format: true,
    });

    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("Function Percentile expects 1 argument").should("not.exist");
    H.CustomExpressionEditor.nameInput().type("Expression name");
    cy.button("Done").should("not.be.disabled").click();
    // Todo: Add positive assertions once this is fixed

    cy.findByTestId("aggregate-step")
      .contains("Expression name")
      .should("exist");
  });
});

describe("issue 14843", () => {
  const { PEOPLE, PEOPLE_ID } = SAMPLE_DATABASE;
  const CC_NAME = "City Length";

  const questionDetails = {
    name: "14843",
    query: {
      "source-table": PEOPLE_ID,
      expressions: { [CC_NAME]: ["length", ["field", PEOPLE.CITY, null]] },
    },
  };

  beforeEach(() => {
    cy.intercept("POST", "/api/dataset").as("dataset");

    H.restore();
    cy.signInAsAdmin();
  });

  it("should correctly filter custom column by 'Not equal to' (metabase#14843)", () => {
    H.createQuestion(questionDetails, { visitQuestion: true });
    H.openNotebook();

    H.filter({ mode: "notebook" });
    H.popover().findByText(CC_NAME).click();
    H.selectFilterOperator("Not equal to");
    H.clauseStepPopover().within(() => {
      H.multiAutocompleteInput().type("3");
      cy.button("Add filter").click();
    });

    H.visualize();

    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText(`${CC_NAME} is not equal to 3`);
    // Rye (length 3) is the city of the 4th person, so it would render without the filter
    H.tableInteractiveBody().findByText("Hudson Borer").should("be.visible");
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("Rye").should("not.exist");
  });
});

describe("issue 18069", () => {
  const questionDetails = {
    name: "18069",
    query: {
      "source-table": PRODUCTS_ID,
      expressions: {
        ["CC_Category"]: ["field", PRODUCTS.CATEGORY, null],
        ["CC_LowerVendor"]: ["lower", ["field", PRODUCTS.VENDOR, null]],
        ["CC_UpperTitle"]: ["upper", ["field", PRODUCTS.TITLE, null]],
        ["CC_HalfPrice"]: ["/", ["field", PRODUCTS.PRICE, null], 2],
        ["CC_ScaledRating"]: ["*", 1.5, ["field", PRODUCTS.RATING, null]],
      },
    },
  };

  beforeEach(() => {
    H.restore();
    cy.signInAsAdmin();

    H.createQuestion(questionDetails).then(({ body: { id: QUESTION_ID } }) => {
      cy.visit(`/question/${QUESTION_ID}/notebook`);
    });
  });

  it("should not allow choosing text fields for SUM (metabase#18069)", () => {
    H.summarize({ mode: "notebook" });
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("Sum of ...").click();

    H.popover().within(() => {
      // regular fields
      cy.findByText("Price");
      cy.findByText("Rating");

      // custom columns not suitable for SUM
      cy.findByText("CC_Category").should("not.exist");
      cy.findByText("CC_LowerVendor").should("not.exist");
      cy.findByText("CC_UpperTitle").should("not.exist");

      // custom columns suitable for SUM
      cy.findByText("CC_HalfPrice");
      cy.findByText("CC_ScaledRating").click();
    });

    H.visualize();

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

describe("issue 18747", () => {
  const questionDetails = {
    name: "18747",
    query: {
      "source-table": ORDERS_ID,
      expressions: {
        ["Quantity_2"]: ["field", ORDERS.QUANTITY, null],
      },
    },
  };
  function addNumberParameterToDashboard() {
    H.editDashboard();

    H.setFilter("Number", "Equal to");
  }

  function mapParameterToCustomColumn() {
    cy.findByTestId("dashcard-container").contains("Select…").click();
    H.popover().contains("Quantity_2").click({ force: true });
  }

  function addValueToParameterFilter() {
    H.filterWidget().click();
    H.dashboardParametersPopover().within(() => {
      H.fieldValuesCombobox().type("14");
      cy.button("Add filter").click();
    });
  }

  beforeEach(() => {
    H.restore();
    cy.signInAsAdmin();

    H.createQuestionAndDashboard({ questionDetails }).then(
      ({ body: { id, card_id, dashboard_id } }) => {
        cy.request("PUT", `/api/dashboard/${dashboard_id}`, {
          cards: [
            {
              id,
              card_id,
              row: 0,
              col: 0,
              size_x: 16,
              size_y: 8,
            },
          ],
        }).then(() => {
          H.visitDashboard(dashboard_id);
        });
      },
    );
  });

  it("should correctly filter the table with a number parameter mapped to the custom column Quantity_2", () => {
    addNumberParameterToDashboard();
    mapParameterToCustomColumn();

    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.contains("Save").click();
    // wait for saving to finish
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.contains("You're editing this dashboard.").should("not.exist");

    addValueToParameterFilter();

    H.tableInteractiveBody().findAllByRole("row").should("have.length", 1);

    // check that the parameter value is parsed correctly on page load
    cy.reload();
    cy.get(".LoadingSpinner").should("not.exist");

    H.tableInteractiveBody().findAllByRole("row").should("have.length", 1);
  });
});

describe("issue 18814", () => {
  const ccName = "Custom Created At";

  const questionDetails = {
    name: "18814",
    query: {
      "source-query": {
        "source-table": ORDERS_ID,
        aggregation: [["count"]],
        breakout: [["field", ORDERS.CREATED_AT, { "temporal-unit": "year" }]],
      },
      expressions: {
        [ccName]: ["field", "CREATED_AT", { "base-type": "type/DateTime" }],
      },
    },
  };

  beforeEach(() => {
    H.restore();
    cy.signInAsAdmin();

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

  it("should be able to use a custom column in aggregation for a nested query (metabase#18814)", () => {
    H.openNotebook();

    cy.icon("sum").click();
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("Count of rows").click();

    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("Pick a column to group by").click();
    H.popover().contains(ccName).click();

    H.visualize();

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

describe("issue 19744", () => {
  const { PRODUCTS_ID, PRODUCTS } = SAMPLE_DATABASE;

  const questionDetails = {
    dataset_query: {
      type: "query",
      query: {
        "source-query": {
          "source-table": PRODUCTS_ID,
          aggregation: [
            ["count"],
            ["sum", ["field", PRODUCTS.PRICE, null]],
            ["sum", ["field", PRODUCTS.RATING, null]],
          ],
          breakout: [["field", PRODUCTS.CATEGORY, null]],
        },
        expressions: { Math: ["+", 1, 1] },
      },
      database: SAMPLE_DB_ID,
    },
    display: "bar",
  };

  beforeEach(() => {
    H.restore();
    cy.signInAsAdmin();
  });

  it("custom column after aggregation shouldn't limit or change the behavior of dashboard filters (metabase#19744)", () => {
    // For this specific repro, it's crucial to first visit the question in order to load the `results_metadata`...
    H.visitQuestionAdhoc(questionDetails);
    // ...and then to save it using the UI
    H.saveQuestion("19744");

    H.setFilter("Date picker", "All Options");

    H.getDashboardCard(1).findByText("Select…").click();
    H.popover().contains("Created At");
  });
});

describe("issue 19745", () => {
  const questionDetails = {
    display: "table",
    query: {
      "source-query": {
        "source-table": PRODUCTS_ID,
        aggregation: [
          ["count"],
          ["sum", ["field", PRODUCTS.PRICE, { "base-type": "type/Float" }]],
        ],
        breakout: [["field", PRODUCTS.CATEGORY, { "base-type": "type/Text" }]],
      },
      fields: [
        ["field", PRODUCTS.CATEGORY, { "base-type": "type/Text" }],
        ["field", "sum", { "base-type": "type/Float" }],
        ["expression", "Custom Column"],
      ],
      expressions: {
        "Custom Column": ["+", 1, 1],
      },
    },
  };

  const filterDetails = {
    id: "b6f1865b",
    name: "Date filter",
    slug: "date",
    type: "date/month-year",
    sectionId: "date",
  };

  const dashboardDetails = {
    name: "Filters",
    parameters: [filterDetails],
  };

  function updateQuestionAndSelectFilter(updateExpressions) {
    H.createQuestionAndDashboard({ questionDetails, dashboardDetails }).then(
      ({ body: { card_id, dashboard_id } }) => {
        H.visitQuestion(card_id);

        // this should modify the query and remove the second stage
        H.openNotebook();
        updateExpressions();
        H.visualize();
        H.openVizSettingsSidebar();
        cy.findByRole("button", { name: "Add or remove columns" }).click();
        cy.findByLabelText("Count").should("not.be.checked").click();
        updateQuestion();

        // as we select all columns in the first stage of the query,
        // it should be possible to map a filter to a selected column
        H.visitDashboard(dashboard_id);
        H.editDashboard();
        cy.findByText("Date filter").click();
        H.selectDashboardFilter(H.getDashboardCard(), "Created At");
        H.saveDashboard();
      },
    );
  }

  function removeExpression(name) {
    H.getNotebookStep("expression", { stage: 1 }).within(() => {
      cy.findByText(name).within(() => {
        cy.icon("close").click();
      });
    });
  }

  function removeAllExpressions() {
    H.getNotebookStep("expression", { stage: 1 }).within(() => {
      cy.findByLabelText("Remove step").click({ force: true });
    });
  }

  function updateQuestion() {
    cy.intercept("PUT", "/api/card/*").as("updateQuestion");
    cy.findByText("Save").click();
    cy.findByTestId("save-question-modal").within((modal) => {
      cy.findByText("Save").click();
    });
    cy.wait("@updateQuestion");
  }

  beforeEach(() => {
    H.restore();
    cy.signInAsAdmin();
  });

  it("should unwrap the nested query when removing the last expression (metabase#19745)", () => {
    updateQuestionAndSelectFilter(() => removeExpression("Custom Column"));
  });

  it("should unwrap the nested query when removing all expressions (metabase#19745)", () => {
    updateQuestionAndSelectFilter(() => removeAllExpressions());
  });
});

describe("issue 20229", () => {
  const questionDetails = {
    name: "20229",
    type: "query",
    query: {
      "source-table": ORDERS_ID,
      expressions: {
        Adjective: [
          "case",
          [[[">", ["field", ORDERS.TOTAL, null], 100], "expensive"]],
          { default: "cheap" },
        ],
      },
      limit: 10,
    },
  };
  function ccAssertion() {
    cy.findByText("Adjective");
    cy.contains("expensive");
    cy.contains("cheap");
  }

  function unselectColumn(column) {
    cy.findByText(column)
      .siblings()
      .find('input[type="checkbox"]')
      .click({ force: true });
  }

  beforeEach(() => {
    H.restore();
    cy.signInAsAdmin();

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

  it("should display custom column regardless of how many columns are selected (metabase#20229)", () => {
    ccAssertion();

    // Switch to the notebook view to deselect at least one column
    H.openNotebook();

    cy.findAllByTestId("fields-picker").click();
    H.popover().within(() => {
      unselectColumn("Tax");
    });

    H.visualize();

    ccAssertion();
  });
});

describe("issue 21135", () => {
  const questionDetails = {
    name: "21135",
    query: {
      "source-table": PRODUCTS_ID,
      limit: 5,
      expressions: { Price: ["+", ["field", PRODUCTS.PRICE, null], 2] },
    },
  };

  function previewCustomColumnNotebookStep() {
    cy.intercept("POST", "/api/dataset").as("dataset");

    cy.findByTestId("step-expression-0-0").find(".Icon-play").click();

    cy.wait("@dataset");
  }

  beforeEach(() => {
    H.restore();
    cy.signInAsAdmin();
    H.createQuestion(questionDetails, { visitQuestion: true });
    H.openNotebook();
  });

  it("should handle cc with the same name as the table column (metabase#21135)", () => {
    cy.findAllByTestId("notebook-cell-item").contains("Price").click();
    cy.button("Update").click();

    previewCustomColumnNotebookStep();

    // We should probably use data-testid or some better selector but it is crucial
    // to narrow the results to the preview area to avoid false positive result.
    cy.findByTestId("preview-root").within(() => {
      cy.findByText("Rustic Paper Wallet");

      // Make sure we see both the original column and the custom column
      cy.findAllByText("Price").should("have.length", 1);
      cy.findAllByText("Price (1)").should("have.length", 1);

      cy.findByText("29.46"); // actual Price column
      cy.findByText("31.46"); // custom column
    });
  });
});

describe("issue 21513", () => {
  beforeEach(() => {
    H.restore();
    cy.signInAsAdmin();
  });

  it("should handle cc with the same name as an aggregation function (metabase#21513)", () => {
    H.openProductsTable({ mode: "notebook" });
    H.summarize({ mode: "notebook" });
    H.popover().findByText("Count of rows").click();

    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("Pick a column to group by").click();
    H.popover().findByText("Category").click();

    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("Custom column").click();
    H.enterCustomColumnDetails({
      formula: "[Count] * 2",
      name: "Double Count",
    });
    cy.button("Done").should("not.be.disabled");
  });
});

describe("issue 23862", () => {
  const questionDetails = {
    name: "23862",
    query: {
      "source-table": ORDERS_ID,
      expressions: {
        CC: [
          "case",
          [[[">", ["field", ORDERS.TOTAL, null], 10], "Large"]],
          {
            default: "Small",
          },
        ],
      },
      aggregation: [["sum", ["field", ORDERS.TOTAL, null]]],
      breakout: [["expression", "CC"]],
    },
  };

  beforeEach(() => {
    H.restore();
    cy.signInAsAdmin();
  });

  it("should group by a custom column and work in a nested question (metabase#23862)", () => {
    H.createQuestion(questionDetails).then(({ body: { id } }) => {
      H.visitQuestionAdhoc(
        {
          dataset_query: {
            type: "query",
            query: {
              "source-table": `card__${id}`,
            },
            database: SAMPLE_DB_ID,
          },
          display: "table",
        },
        {
          callback: (xhr) => expect(xhr.response.body.error).not.to.exist,
        },
      );
    });

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

describe("issue 24922", () => {
  const segmentDetails = {
    name: "OrdersSegment",
    description: "All orders with a total under $100.",
    definition: {
      database: SAMPLE_DB_ID,
      type: "query",
      query: {
        "source-table": ORDERS_ID,
        filter: ["<", ["field", ORDERS.TOTAL, null], 100],
      },
    },
  };

  const customColumnDetails = {
    name: "CustomColumn",
    formula: 'case([OrdersSegment], "Segment", "Other")',
  };

  beforeEach(() => {
    H.restore();
    cy.signInAsAdmin();
    H.createSegment(segmentDetails);
  });

  it("should allow segments in case custom expressions (metabase#24922)", () => {
    H.openOrdersTable({ mode: "notebook" });

    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("Custom column").click();
    H.enterCustomColumnDetails(customColumnDetails);
    cy.button("Done").click();

    H.visualize(({ body }) => {
      expect(body.error).to.not.exist;
    });
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("CustomColumn").should("be.visible");
    // The first order's total is under 100, the second one's is not
    H.tableInteractiveBody()
      .findAllByText("Segment")
      .first()
      .should("be.visible");
    H.tableInteractiveBody()
      .findAllByText("Other")
      .first()
      .should("be.visible");
  });
});

["postgres" /*, "mysql" */].forEach((dialect) => {
  describe(`issue 27745 (${dialect})`, { tags: "@external" }, () => {
    const tableName = "colors27745";

    beforeEach(() => {
      H.restore(`${dialect}-writable`);
      cy.signInAsAdmin();

      H.resetTestTable({ type: dialect, table: tableName });
      cy.request("POST", `/api/database/${WRITABLE_DB_ID}/sync_schema`);
      cy.intercept("GET", "/api/search*").as("search");
    });

    it("should display all summarize options if the only numeric field is a custom column (metabase#27745)", () => {
      H.startNewQuestion();

      H.miniPicker().within(() => {
        cy.realType("colors");
        cy.wait("@search");
        cy.contains(/colors/i).click();
      });
      cy.findByLabelText("Custom column").click();
      H.enterCustomColumnDetails({
        formula: "case([ID] > 1, 25, 5)",
        name: "Numeric",
      });
      cy.button("Done").click();

      H.visualize();

      H.tableHeaderClick("Numeric");
      H.popover().findByText(/^Sum$/).click();

      cy.wait("@dataset");
      cy.findByTestId("scalar-value").invoke("text").should("eq", "55");

      cy.findByTestId("sidebar-right")
        .should("be.visible")
        .within(() => {
          cy.findByTestId("aggregation-item").should(
            "contain",
            "Sum of Numeric",
          );
        });
    });
  });
});

describe("issue 49342", () => {
  beforeEach(() => {
    H.restore();
    cy.signInAsNormalUser();
  });

  it("should not be possible to leave the expression input with the Tab key ", () => {
    // This test used to be a repro for #49342, but the product feature changed
    // so that the expression input can no longer be tabbed out of.

    H.openOrdersTable({ mode: "notebook" });
    cy.findByLabelText("Custom column").click();
    H.enterCustomColumnDetails({ formula: "[Tot{Enter}", blur: false });
    cy.realPress("Tab");
    H.CustomExpressionEditor.value().should("equal", "[Total]  ");
    H.CustomExpressionEditor.nameInput().should("not.be.focused");

    cy.log("Shift-tab from name input should stay within the popover");
    H.CustomExpressionEditor.nameInput().focus();
    H.CustomExpressionEditor.nameInput().realPress(["Shift", "Tab"]);
    H.CustomExpressionEditor.nameInput().realPress(["Shift", "Tab"]);
    H.CustomExpressionEditor.nameInput().realPress(["Shift", "Tab"]);
    cy.focused().should("have.attr", "role", "textbox");

    cy.realPress(["Shift", "Tab"]);
    cy.button("Cancel").should("be.focused");

    cy.realPress(["Shift", "Tab"]);
    H.CustomExpressionEditor.nameInput().should("be.focused");
  });
});

describe("issue 49882", () => {
  beforeEach(() => {
    H.restore();
    cy.signInAsNormalUser();
    H.openOrdersTable({ mode: "notebook" });
    cy.findByTestId("head-crumbs-container")
      .should("contain", "Sample Database")
      .and("contain", "Orders");
    H.addCustomColumn();
  });

  it("should not eat up subsequent characters when applying a suggestion (metabase#49882-1)", () => {
    const moveCursorTo2ndCaseArgument = "{leftarrow}".repeat(6);
    H.enterCustomColumnDetails({
      formula: `case([Total] > 200, , "X")${moveCursorTo2ndCaseArgument}[tot`,
      blur: false,
    });

    H.CustomExpressionEditor.completions().should("be.visible");
    cy.realPress("Enter", { pressDelay: 10 });

    H.CustomExpressionEditor.value().should(
      "equal",
      'case([Total] > 200, [Total], "X")',
    );
    H.popover()
      .findByText("Expecting a closing parenthesis")
      .should("not.exist");
  });

  it(
    "does not clear expression input when expression is invalid (metabase#49882-2, metabase#15892)",
    {
      defaultCommandTimeout: 15000, // makes test less flaky
    },
    () => {
      // This test used to use keyboard shortcuts to cut and paste but this
      // seem impossible to emulate with CodeMirror in Cypress, so it's using
      // a synthetic paste event instead.
      // Copy is impossible to emulate so far, but it's not crucial to test the issue.

      H.enterCustomColumnDetails({
        formula:
          'case([Tax] > 1, case([Total] > 200, [Total], "Nothing"), [Tax])',
        blur: false,
      });

      // "Cut" [Tax]
      H.CustomExpressionEditor.type("{end}{leftarrow}", {
        focus: false,
        blur: false,
      });
      cy.realPress(["Shift", "ArrowLeft"]);
      cy.realPress(["Shift", "ArrowLeft"]);
      cy.realPress(["Shift", "ArrowLeft"]);
      cy.realPress(["Shift", "ArrowLeft"]);
      cy.realPress(["Shift", "ArrowLeft"]);
      cy.realPress(["Backspace"]);

      H.CustomExpressionEditor.type("{leftarrow}".repeat(42), {
        focus: false,
        blur: false,
      });

      // Paste [Tax] before case
      H.CustomExpressionEditor.paste("[Tax]");

      H.CustomExpressionEditor.value().should(
        "equal",
        'case([Tax] > 1,[Tax] case([Total] > 200, [Total], "Nothing"), )',
      );

      H.popover()
        .findByText("Expecting operator but got case instead")
        .should("be.visible", { timeout: 5000 });
    },
  );

  it("should update currently selected suggestion when suggestions list is updated (metabase#49882-4)", () => {
    const selectProductRating =
      "{downarrow}{downarrow}{downarrow}{downarrow}{downarrow}";

    H.enterCustomColumnDetails({
      formula: `[Produ${selectProductRating}`,
      blur: false,
    });

    H.CustomExpressionEditor.completion("Product → Rating").should(
      "be.visible",
    );
    H.CustomExpressionEditor.acceptCompletion("tab");

    H.CustomExpressionEditor.value().should("equal", "[Product → Rating]");
    cy.focused().should("have.attr", "role", "textbox");
  });
});

describe("issue 49304", () => {
  const questionDetails = {
    query: {
      "source-table": PRODUCTS_ID,
    },
  };

  beforeEach(() => {
    H.restore();
    cy.signInAsNormalUser();
  });

  it("should be possible to switch between filter widgets and the expression editor for multi-argument operators (metabase#49304)", () => {
    H.createQuestion(questionDetails, { visitQuestion: true });
    H.openNotebook();

    cy.log(
      "add a filter using a filter widget and check that it is rendered in the expression editor",
    );
    H.getNotebookStep("data").button("Filter").click();
    H.popover().findByText("Category").click();
    H.selectFilterOperator("Contains");
    H.clauseStepPopover().within(() => {
      cy.findByPlaceholderText("Enter some text").type("gadget,widget");
      cy.button("Add filter").click();
    });
    H.getNotebookStep("filter")
      .findByText("Category contains 2 selections")
      .click();
    H.clauseStepPopover().within(() => {
      cy.button("Back").click();
      cy.findByText("Custom Expression").click();
      H.CustomExpressionEditor.value().should(
        "equal",
        dedent`
          contains(
            [Category],
            "gadget",
            "widget",
            "case-insensitive"
          )
        `.trim(),
      );
    });

    cy.log(
      "modify the expression in the expression editor and make sure it is rendered correctly in the filter widget",
    );
    H.popover().within(() => {
      H.enterCustomColumnDetails({
        formula:
          'contains([Category], "gadget", "widget", "gizmo", "case-insensitive")',
      });
      cy.button("Update").click();
    });
    H.getNotebookStep("filter")
      .findByText("Category contains 3 selections")
      .click();
    H.popover().within(() => {
      cy.findByText("gadget").should("be.visible");
      cy.findByText("widget").should("be.visible");
      cy.findByText("gizmo").should("be.visible");
      cy.findByLabelText("Case sensitive").should("not.be.checked");
    });

    cy.log(
      "change options in the filter widget and make sure they get reflected in the expression editor",
    );
    H.popover().within(() => {
      cy.findByLabelText("Case sensitive").click();
      cy.button("Update filter").click();
    });
    H.getNotebookStep("filter")
      .findByText("Category contains 3 selections")
      .click();
    H.popover().within(() => {
      cy.button("Back").click();
      cy.findByText("Custom Expression").click();
      H.CustomExpressionEditor.value().should(
        "equal",
        'contains([Category], "gadget", "widget", "gizmo")',
      );
    });

    cy.log(
      "remove options from the expression in the expression editor and make sure it is rendered correctly in the filter widget",
    );
    H.popover().within(() => {
      H.enterCustomColumnDetails({
        formula: 'contains([Category], "gadget", "widget", "gizmo")',
      });
      cy.button("Update").click();
    });
    H.getNotebookStep("filter")
      .findByText("Category contains 3 selections")
      .click();
    H.popover().within(() => {
      cy.findByText("gadget").should("be.visible");
      cy.findByText("widget").should("be.visible");
      cy.findByText("gizmo").should("be.visible");
      cy.findByLabelText("Case sensitive").should("be.checked");
    });
  });
});

describe("issue 49305", () => {
  beforeEach(() => {
    H.restore();
    cy.signInAsAdmin();
  });

  it("should be able to use a custom column in sort for a nested query (metabase#49305)", () => {
    const ccName = "CC Title";

    // This bug does not reproduce if the base question is created via H.createQuestion or H.visitQuestionAdhoc, so create it manually in the UI.
    cy.visit("/");
    H.newButton("Question").click();
    H.miniPicker().within(() => {
      cy.findByText("Sample Database").click();
      cy.findByText("Products").click();
    });
    H.getNotebookStep("data").button("Custom column").click();
    H.enterCustomColumnDetails({
      formula: 'concat("49305 ", [Title])',
      name: ccName,
      allowFastSet: true,
    });
    H.popover().button("Done").click();
    H.saveQuestion(
      "49305 Base question",
      { wrapId: true },
      { path: ["Our analytics"], select: true },
    );

    cy.get("@questionId").then((id) => {
      const nestedQuestion = {
        dataset_query: {
          database: SAMPLE_DB_ID,
          query: {
            "source-table": `card__${id}`,
            aggregation: [["count"]],
            breakout: [["field", ccName, { "base-type": "type/Text" }]],
            limit: 2,
          },
          type: "query",
        },
      };

      H.visitQuestionAdhoc(nestedQuestion, { mode: "notebook" });

      // Verify that a sort step can be added via the UI. This is the bug we are validating.
      cy.button("Sort").click();
      H.popover().contains(ccName).click();
      H.getNotebookStep("sort").contains(ccName).click();

      H.verifyNotebookQuery("49305 Base question", [
        {
          aggregations: ["Count"],
          breakouts: [ccName],
          limit: 2,
          sort: [{ column: ccName, order: "desc" }],
        },
      ]);

      H.visualize();
      cy.findByLabelText("Switch to data").click();
      H.assertTableData({
        columns: ["CC Title", "Count"],
        firstRows: [
          ["49305 Synergistic Wool Coat", "1"],
          ["49305 Synergistic Steel Chair", "1"],
        ],
      });
    });
  });
});

describe("issue 50925", () => {
  const questionDetails = {
    query: {
      "source-table": PRODUCTS_ID,
      expressions: {
        Custom: [
          "case",
          [
            [
              [
                "=",
                ["field", PRODUCTS.ID, { "base-type": "type/BigInteger" }],
                1,
              ],
              [
                "*",
                ["field", PRODUCTS.PRICE, { "base-type": "type/Float" }],
                1.21,
              ],
            ],
          ],
          {
            default: ["field", PRODUCTS.PRICE, { "base-type": "type/Float" }],
          },
        ],
      },
    },
  };

  beforeEach(() => {
    H.restore();
    cy.signInAsNormalUser();
  });

  it("should not remove existing characters when applying autocomplete suggestion (metabase#50925)", () => {
    H.createQuestion(questionDetails, { visitQuestion: true });
    H.openNotebook();

    cy.log("incomplete bracket identifier is followed by whitespace");
    H.getNotebookStep("expression").findByText("Custom").click();

    H.CustomExpressionEditor.focus()
      .type("{leftarrow}".repeat(9))
      .type(" [Pr", { focus: false });

    H.CustomExpressionEditor.completions().should("be.visible");
    H.CustomExpressionEditor.get().realPress("Enter", { pressDelay: 10 });

    H.CustomExpressionEditor.blur()
      .value()
      .should("equal", "case([ID] = 1, [Price] * 1.21, [Price] [Price])");

    cy.log("incomplete bracket identifier is followed by bracket identifier");
    H.popover().button("Cancel").click();
    H.getNotebookStep("expression").findByText("Custom").click();

    H.CustomExpressionEditor.focus()
      .type("{leftarrow}".repeat(8))
      .type("[Pr", { focus: false });

    H.CustomExpressionEditor.completions().should("be.visible");
    H.CustomExpressionEditor.get().realPress("Enter", { pressDelay: 10 });

    H.CustomExpressionEditor.blur()
      .value()
      .should(
        "match",
        /^case\(\[ID\] = 1, \[Price\] \* 1\.21, \[Price\]\s*\[Price\]\)$/,
      );
  });
});

describe("issue 53682", () => {
  beforeEach(() => {
    H.restore();
    cy.signInAsNormalUser();
  });

  it("should show an error message when trying to use a multi-arg expression function with not enough arguments (metabase#53682)", () => {
    H.openProductsTable({ mode: "notebook" });
    H.getNotebookStep("data").button("Custom column").click();
    H.enterCustomColumnDetails({
      formula: "contains([Category])",
    });
    H.popover().within(() => {
      cy.findByText("Function contains expects at least 2 arguments").should(
        "be.visible",
      );
      cy.button("Done").should("be.disabled");
    });

    cy.log("Editing the name should not crash the editor");
    H.CustomExpressionEditor.nameInput().click().type("Name");
    H.expressionEditorWidget().should("be.visible");
    H.CustomExpressionEditor.nameInput().should("have.value", "Name");
    H.popover()
      .findByText("Function contains expects at least 2 arguments")
      .should("be.visible");
  });
});

describe("issue 53527", () => {
  const nativeQuestionDetails = {
    name: "Quotes SQL",
    native: {
      query: "SELECT 'a\"b' AS TEXT",
      "template-tags": {},
    },
  };

  const mbqlQuestionDetails = (cardId) => ({
    name: "Quotes MBQL",
    query: {
      "source-table": `card__${cardId}`,
    },
  });

  beforeEach(() => {
    H.restore();
    cy.signInAsNormalUser();
  });

  it("should properly unescape quotes in the expression editor (metabase#53527)", () => {
    H.createNativeQuestion(nativeQuestionDetails).then(({ body: card }) => {
      H.createQuestion(mbqlQuestionDetails(card.id), { visitQuestion: true });
    });
    H.openNotebook();
    H.getNotebookStep("data").button("Custom column").click();
    H.enterCustomColumnDetails({
      formula: 'replace([TEXT], "\\"", "")',
      name: "CustomColumn",
    });
    H.popover().button("Done").click();
    H.visualize();
    H.tableInteractive().findByText("ab").should("be.visible");
  });
});