Skip to content

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

e2e2unit: Filters relative datetime (#85722)

Nemanja Glumacb525862dbd6c
diff --git a/e2e/test/scenarios/filters/relative-datetime.cy.spec.js b/e2e/test/scenarios/filters/relative-datetime.cy.spec.js
index e63e9c543b7..be487f4345d 100644
--- a/e2e/test/scenarios/filters/relative-datetime.cy.spec.js
+++ b/e2e/test/scenarios/filters/relative-datetime.cy.spec.js
@@ -1,300 +1,30 @@
-import { dayjs } from "metabase/dayjs";
-
const { H } = cy;
-const STARTING_FROM_UNITS = [
- "minutes",
- "hours",
- "days",
- "weeks",
- "months",
- "quarters",
- "years",
-];
-
describe("scenarios > question > relative-datetime", () => {
beforeEach(() => {
H.restore();
cy.signInAsNormalUser();
});
- describe("starting from", () => {
- STARTING_FROM_UNITS.forEach((unit) =>
- it(`should work with Past filters (${unit} ago)`, () => {
- const now = dayjs().utc();
- nativeSQL([
- now,
- now.add(-1, unit),
- now.add(-14, unit),
- now.add(-15, unit),
- now.add(-30, unit),
- ]);
- withStartingFrom("Previous", [10, unit], [10, unit]);
- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
- cy.findByText("Showing 2 rows").should("exist");
- }),
- );
-
- STARTING_FROM_UNITS.forEach((unit) =>
- it(`should work with Next filters (${unit} from now)`, () => {
- const now = dayjs().utc();
- nativeSQL([
- now,
- now.add(1, unit),
- now.add(14, unit),
- now.add(15, unit),
- now.add(30, unit),
- ]);
- withStartingFrom("Next", [10, unit], [10, unit]);
- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
- cy.findByText("Showing 2 rows").should("exist");
- }),
- );
-
- it("should not clobber filter when value is set to 1", () => {
- H.openOrdersTable();
-
- H.tableHeaderClick("Created At");
-
- H.popover().within(() => {
- cy.findByText("Filter by this column").click();
- cy.findByText("Previous 30 days").should("be.visible");
- cy.icon("chevronleft").should("not.exist");
- cy.findByText("Previous 30 days").click();
- });
-
- cy.wait("@dataset");
+ it("starting from option should set correct sign (metabase#22228)", () => {
+ H.openOrdersTable();
- cy.findByTestId("qb-filters-panel")
- .findByText("Created At is in the previous 30 days")
- .click();
-
- setRelativeDatetimeValue(1);
- setRelativeDatetimeUnit("year");
- addStartingFrom();
- setStartingFromValue(2);
-
- H.popover().button("Update filter").click();
- cy.wait("@dataset");
-
- cy.findByTestId("qb-filters-panel")
- .findByText("Created At is in the previous year, starting 2 years ago")
- .should("be.visible");
+ H.tableHeaderClick("Created At");
+ H.popover().within(() => {
+ cy.findByText("Filter by this column").click();
+ cy.findByText("Relative date range…").click();
+ cy.findByText("Next").click();
+ cy.findByLabelText(/Starting from/).click();
+ cy.button("Add filter").click();
});
- });
+ cy.wait("@dataset");
- function assertOptions(expectedOptions) {
- cy.findAllByRole("option").should(($options) => {
- expect(Cypress._.map($options, "textContent")).to.deep.equal(
- expectedOptions,
+ cy.findByTestId("qb-filters-panel").within(() => {
+ const baseName = "Created At is in the next 30 days";
+ cy.findByText(`${baseName}, starting 7 days from now`).should(
+ "be.visible",
);
- });
- }
-
- describe("basic functionality", () => {
- it("starting from should contain units only equal or greater than the filter unit", () => {
- H.openOrdersTable();
-
- H.tableHeaderClick("Created At");
- H.clickActionsPopover().within(() => {
- cy.findByText("Filter by this column").click();
- cy.findByText("Relative date range…").click();
- });
-
- addStartingFrom();
-
- H.clickActionsPopover()
- .findByRole("textbox", { name: "Starting from unit" })
- .click();
-
- assertOptions([
- "days ago",
- "weeks ago",
- "months ago",
- "quarters ago",
- "years ago",
- ]);
-
- setRelativeDatetimeUnit(/quarters/);
- H.clickActionsPopover()
- .findByRole("textbox", { name: "Starting from unit" })
- .click();
-
- assertOptions(["quarters ago", "years ago"]);
- });
-
- it("should go back to shortcuts view", () => {
- H.openOrdersTable();
-
- H.tableHeaderClick("Created At");
- H.popover().within(() => {
- cy.findByText("Filter by this column").click();
- cy.findByText("Fixed date range…").click();
- cy.icon("chevronleft").first().click();
- cy.findByText("Fixed date range…").should("exist");
- cy.findByText("Between").should("not.exist");
- });
- });
-
- it("relative dates should default to past filter and current filters should work (metabase#22027, metabase#21977)", () => {
- H.openOrdersTable();
-
- H.tableHeaderClick("Created At");
- H.popover().within(() => {
- cy.findByText("Filter by this column").click();
- cy.findByText("Relative date range…").click();
- cy.findByDisplayValue("days").should("exist");
- cy.findByText("Day").should("not.exist");
- cy.findByText("Quarter").should("not.exist");
- cy.findByText("Month").should("not.exist");
- cy.findByText("Year").should("not.exist");
-
- cy.findByText("Current").click();
- cy.findByText("Year").click();
- });
- cy.wait("@dataset");
-
- H.queryBuilderMain()
- .findByText("There was a problem with your question")
- .should("not.exist");
-
- cy.findByTestId("qb-filters-panel")
- .findByText("Created At is this year")
- .should("be.visible");
- });
-
- it("should match the starting from units and allow changing values with starting from (metabase#22222, metabase#22227)", () => {
- H.openOrdersTable();
-
- openCreatedAt("Previous");
- addStartingFrom();
- setRelativeDatetimeUnit("months");
- H.clickActionsPopover().within(() => {
- cy.findByDisplayValue("months ago").should("exist");
- cy.findByDisplayValue("days ago").should("not.exist");
- });
- setRelativeDatetimeValue(1);
- H.popover().button("Add filter").click();
- cy.wait("@dataset");
-
- cy.findByTestId("qb-filters-panel")
- .findByText(
- "Created At is in the previous month, starting 7 months ago",
- )
- .click();
- setRelativeDatetimeValue(3);
- H.popover().button("Update filter").click();
- cy.wait("@dataset");
-
- cy.findByTestId("qb-filters-panel")
- .findByText(
- "Created At is in the previous 3 months, starting 7 months ago",
- )
- .click();
- setStartingFromValue(30);
- H.popover().button("Update filter").click();
- cy.wait("@dataset");
-
- cy.findByTestId("qb-filters-panel")
- .findByText(
- "Created At is in the previous 3 months, starting 30 months ago",
- )
- .should("be.visible");
- });
-
- it("starting from option should set correct sign (metabase#22228)", () => {
- H.openOrdersTable();
-
- openCreatedAt("Next");
- addStartingFrom();
- H.popover().button("Add filter").click();
- cy.wait("@dataset");
-
- cy.findByTestId("qb-filters-panel").within(() => {
- const baseName = "Created At is in the next 30 days";
- cy.findByText(`${baseName}, starting 7 days from now`).should(
- "be.visible",
- );
- cy.findByText(`${baseName}, starting 7 days ago`).should("not.exist");
- });
+ cy.findByText(`${baseName}, starting 7 days ago`).should("not.exist");
});
});
});
-
-const nativeSQL = (values) => {
- cy.intercept("POST", "/api/dataset").as("dataset");
-
- const queries = values.map((value) => {
- const date = dayjs(value).utc();
- return `SELECT '${date.toISOString()}'::timestamp as "testcol"`;
- });
-
- H.createNativeQuestion(
- {
- name: "datetime",
- native: {
- query: queries.join(" UNION ALL "),
- },
- },
- { visitQuestion: true },
- );
-
- cy.findByText("Explore results").click();
- cy.wait("@dataset");
-};
-
-const openCreatedAt = (tab) => {
- H.tableHeaderClick("Created At");
- H.popover().within(() => {
- cy.findByText("Filter by this column").click();
- cy.findByText("Relative date range…").click();
- if (tab) {
- cy.findByText(tab).click();
- }
- });
-};
-
-const addStartingFrom = () => {
- H.popover()
- .findByLabelText(/Starting from/)
- .click();
-};
-
-const setRelativeDatetimeUnit = (unit) => {
- cy.findByRole("textbox", { name: "Unit" }).click();
- cy.findByRole("option", { name: unit }).click();
-};
-
-const setRelativeDatetimeValue = (value) => {
- cy.findByLabelText("Interval").click().clear().type(value).blur();
-};
-
-const setStartingFromValue = (value) => {
- cy.findByLabelText("Starting from interval")
- .click()
- .clear()
- .type(value)
- .blur();
-};
-
-const withStartingFrom = (dir, [num, unit], [startNum, startUnit]) => {
- H.tableHeaderClick("testcol");
- cy.findByTextEnsureVisible("Filter by this column").click();
- cy.findByTextEnsureVisible("Relative date range…").click();
- H.clickActionsPopover().within(() => {
- cy.findByText(dir).click();
- });
-
- H.relativeDatePicker.setValue({ unit, value: num }, H.clickActionsPopover);
- H.relativeDatePicker.addStartingFrom(
- {
- value: startNum,
- unit: startUnit + (dir === "Previous" ? " ago" : " from now"),
- },
- H.clickActionsPopover,
- );
-
- cy.intercept("POST", "/api/dataset").as("dataset");
- H.clickActionsPopover().within(() => cy.findByText("Add filter").click());
- cy.wait("@dataset");
-};
diff --git a/frontend/src/metabase/querying/common/components/DatePicker/RelativeDatePicker/DateOffsetIntervalPicker/DateOffsetIntervalPicker.unit.spec.tsx b/frontend/src/metabase/querying/common/components/DatePicker/RelativeDatePicker/DateOffsetIntervalPicker/DateOffsetIntervalPicker.unit.spec.tsx
index 43ad9c03d63..608616dbe82 100644
--- a/frontend/src/metabase/querying/common/components/DatePicker/RelativeDatePicker/DateOffsetIntervalPicker/DateOffsetIntervalPicker.unit.spec.tsx
+++ b/frontend/src/metabase/querying/common/components/DatePicker/RelativeDatePicker/DateOffsetIntervalPicker/DateOffsetIntervalPicker.unit.spec.tsx
@@ -5,6 +5,7 @@ import { renderWithProviders, screen } from "__support__/ui";
import { waitForFloatingPosition } from "__support__/utils";
import { DATE_PICKER_UNITS } from "metabase/querying/common/constants";
import type {
+ DatePickerTruncationUnit,
DatePickerUnit,
RelativeDatePickerValue,
RelativeIntervalDirection,
@@ -313,6 +314,25 @@ describe("DateOffsetIntervalPicker", () => {
).not.toBeInTheDocument();
});
+ it.each<[DatePickerTruncationUnit, string[]]>([
+ ["day", ["days", "weeks", "months", "quarters", "years"]],
+ ["quarter", ["quarters", "years"]],
+ ])(
+ "should list offset units in order for a %s unit",
+ async (unit, offsetUnits) => {
+ await setup({ value: { ...defaultValue, unit } });
+
+ await userEvent.click(
+ screen.getByRole("textbox", { name: "Starting from unit" }),
+ );
+
+ const suffix = direction === "past" ? "ago" : "from now";
+ expect(
+ screen.getAllByRole("option").map((option) => option.textContent),
+ ).toEqual(offsetUnits.map((offsetUnit) => `${offsetUnit} ${suffix}`));
+ },
+ );
+
it("should display the actual date range", async () => {
await setup({
value: defaultValue,
diff --git a/frontend/src/metabase/querying/common/components/DatePicker/RelativeDatePicker/RelativeDatePicker.unit.spec.tsx b/frontend/src/metabase/querying/common/components/DatePicker/RelativeDatePicker/RelativeDatePicker.unit.spec.tsx
index 398ea6944fd..fc06e05d104 100644
--- a/frontend/src/metabase/querying/common/components/DatePicker/RelativeDatePicker/RelativeDatePicker.unit.spec.tsx
+++ b/frontend/src/metabase/querying/common/components/DatePicker/RelativeDatePicker/RelativeDatePicker.unit.spec.tsx
@@ -67,6 +67,43 @@ describe("RelativeDatePicker", () => {
},
);
+ it("should default to the past tab with a day unit", () => {
+ setup();
+
+ expect(screen.getByRole("tab", { name: "Previous" })).toHaveAttribute(
+ "aria-selected",
+ "true",
+ );
+ expect(screen.getByRole("textbox", { name: "Unit" })).toHaveValue("days");
+ });
+
+ it("should update an existing value to a single unit with an offset", async () => {
+ const { onChange } = setup({
+ value: { type: "relative", value: -30, unit: "day" },
+ });
+
+ const input = screen.getByLabelText("Interval");
+ await userEvent.clear(input);
+ await userEvent.type(input, "1");
+ await userEvent.click(screen.getByRole("textbox", { name: "Unit" }));
+ await userEvent.click(screen.getByRole("option", { name: "year" }));
+ await userEvent.click(await screen.findByLabelText("Starting from…"));
+ const offsetInput = screen.getByLabelText("Starting from interval");
+ await userEvent.clear(offsetInput);
+ await userEvent.type(offsetInput, "2");
+ await userEvent.click(screen.getByText("Apply"));
+
+ expect(onChange).toHaveBeenCalledTimes(1);
+ expect(onChange).toHaveBeenCalledWith({
+ type: "relative",
+ value: -1,
+ unit: "year",
+ offsetValue: -2,
+ offsetUnit: "year",
+ options: undefined,
+ });
+ });
+
it("should not lose values when navigating from Past to Next tab", async () => {
setup();
diff --git a/frontend/src/metabase/querying/filters/utils/dates.unit.spec.ts b/frontend/src/metabase/querying/filters/utils/dates.unit.spec.ts
index b0d4cc112f9..496e60f581c 100644
--- a/frontend/src/metabase/querying/filters/utils/dates.unit.spec.ts
+++ b/frontend/src/metabase/querying/filters/utils/dates.unit.spec.ts
@@ -1,4 +1,7 @@
-import type { DateFilterValue } from "metabase/querying/common/types";
+import type {
+ DateFilterValue,
+ DatePickerTruncationUnit,
+} from "metabase/querying/common/types";
import { setLocalization } from "metabase/utils/i18n";
import * as Lib from "metabase-lib";
import {
@@ -118,6 +121,27 @@ describe("getDateFilterClause", () => {
},
displayName: "Created At is in the previous 2 years, starting 1 year ago",
},
+ {
+ value: {
+ type: "relative",
+ value: -1,
+ unit: "year",
+ offsetValue: -2,
+ offsetUnit: "year",
+ },
+ displayName: "Created At is in the previous year, starting 2 years ago",
+ },
+ {
+ value: {
+ type: "relative",
+ value: 30,
+ unit: "day",
+ offsetValue: 7,
+ offsetUnit: "day",
+ },
+ displayName:
+ "Created At is in the next 30 days, starting 7 days from now",
+ },
{
value: { type: "relative", value: 4, unit: "month" },
displayName: "Created At is in the next 4 months",
@@ -175,6 +199,41 @@ describe("getDateFilterClause", () => {
});
},
);
+
+ it.each<[DatePickerTruncationUnit, string]>([
+ ["minute", "minutes"],
+ ["hour", "hours"],
+ ["day", "days"],
+ ["week", "weeks"],
+ ["month", "months"],
+ ["quarter", "quarters"],
+ ["year", "years"],
+ ])(
+ "should convert a relative filter value with a %s offset to a filter clause",
+ (unit, pluralUnit) => {
+ const pastFilter = getDateFilterClause(column, {
+ type: "relative",
+ value: -10,
+ unit,
+ offsetValue: -10,
+ offsetUnit: unit,
+ });
+ const futureFilter = getDateFilterClause(column, {
+ type: "relative",
+ value: 10,
+ unit,
+ offsetValue: 10,
+ offsetUnit: unit,
+ });
+
+ expect(Lib.displayInfo(query, stageIndex, pastFilter)).toMatchObject({
+ displayName: `Created At is in the previous 10 ${pluralUnit}, starting 10 ${pluralUnit} ago`,
+ });
+ expect(Lib.displayInfo(query, stageIndex, futureFilter)).toMatchObject({
+ displayName: `Created At is in the next 10 ${pluralUnit}, starting 10 ${pluralUnit} from now`,
+ });
+ },
+ );
});
type DateFilterDisplayNameCase = {
diff --git a/test/metabase/query_processor/date_bucketing_test.clj b/test/metabase/query_processor/date_bucketing_test.clj
index f1f7770198e..a3a9555d43e 100644
--- a/test/metabase/query_processor/date_bucketing_test.clj
+++ b/test/metabase/query_processor/date_bucketing_test.clj
@@ -1262,6 +1262,10 @@
"Dynamically generated dataset with 60 checkins spaced 24 hours apart, from 30 days ago to 29 days in the future."
(dataset-def-with-timestamps (* 24 (u/minutes->seconds 60)) 60))
+(def ^:private checkins:1-per-10-days
+ "Dynamically generated dataset with 240 checkins spaced 10 days apart, from 1200 days ago to 1190 days in the future."
+ (dataset-def-with-timestamps (* 10 24 (u/minutes->seconds 60)) 240))
+
(defn- checkins-db-is-old?
"Determine whether we need to recreate one of the dynamically-generated datasets above, if the data has grown a little
stale."
@@ -1409,6 +1413,31 @@
(ffirst
(mt/formatted-rows [int] (qp/process-query query))))))))))
+(deftest ^:parallel relative-time-interval-per-unit-test
+ (mt/test-drivers
+ (mt/normal-drivers-with-feature :date-arithmetics :test/dynamic-dataset-loading)
+ (testing "\"Previous/Next 1 unit, starting 1 unit ago/from now\" returns the rows of the bucket 2 units away"
+ (let [check-units (fn [units]
+ (doseq [unit units
+ n [-1 1]]
+ (testing (format "%s %s" n unit)
+ (let [timestamp [:field (mt/id :checkins :timestamp) nil]
+ ;; Count, first and last timestamp: windows of the same size can have the same count.
+ summary (fn [filter-clause]
+ (mt/first-row
+ (mt/run-mbql-query checkins
+ {:aggregation [[:count] [:min timestamp] [:max timestamp]]
+ :filter filter-clause})))
+ expected (summary [:= (assoc timestamp 2 {:temporal-unit unit})
+ [:relative-datetime (* 2 n) unit]])]
+ (is (pos? (first expected)))
+ (is (= expected
+ (summary [:relative-time-interval timestamp n unit n unit])))))))]
+ (mt/dataset checkins:1-per-day:60
+ (check-units [:day :week]))
+ (mt/dataset checkins:1-per-10-days
+ (check-units [:month :quarter :year]))))))
+
;; Make sure that when referencing the same field multiple times with different units we return the one that actually
;; reflects the units the results are in. eg when we breakout by one unit and filter by another, make sure the results
;; and the col info use the unit used by breakout