Skip to content

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

Require selecting an alert schedule time (#79623)

Egor Grushineb009eb8f938
diff --git a/e2e/support/helpers/e2e-notification-helpers.ts b/e2e/support/helpers/e2e-notification-helpers.ts
index 37d431a4966..006354b245b 100644
--- a/e2e/support/helpers/e2e-notification-helpers.ts
+++ b/e2e/support/helpers/e2e-notification-helpers.ts
@@ -5,6 +5,11 @@ export const getAlertChannel = (name: string) =>
name,
});
+export const selectScheduleTime = (time = "8:00") => {
+ cy.findByTestId("select-time").click();
+ cy.findByRole("option", { name: time }).click();
+};
+
export const WEBHOOK_TEST_SESSION_ID = "00000000-0000-0000-0000-000000000000";
export const WEBHOOK_TEST_HOST = "http://127.0.0.1:9080";
diff --git a/e2e/test-component/scenarios/embedding-sdk/interactive-question.cy.spec.tsx b/e2e/test-component/scenarios/embedding-sdk/interactive-question.cy.spec.tsx
index f6a84d9dcf0..9df9b88ff0e 100644
--- a/e2e/test-component/scenarios/embedding-sdk/interactive-question.cy.spec.tsx
+++ b/e2e/test-component/scenarios/embedding-sdk/interactive-question.cy.spec.tsx
@@ -2,7 +2,7 @@ const { H } = cy;
import { InteractiveQuestion } from "@metabase/embedding-sdk-react";
import { ORDERS_QUESTION_ID } from "e2e/support/cypress_sample_instance_data";
-import { modal, popover } from "e2e/support/helpers";
+import { modal, popover, selectScheduleTime } from "e2e/support/helpers";
import { getSdkRoot } from "e2e/support/helpers/e2e-embedding-sdk-helpers";
import { mountSdkContent } from "e2e/support/helpers/embedding-sdk-component-testing/component-embedding-sdk-helpers";
import { signInAsAdminAndEnableEmbeddingSdk } from "e2e/support/helpers/embedding-sdk-testing";
@@ -135,6 +135,7 @@ describe("scenarios > embedding-sdk > interactive-question", () => {
cy.log("alerts modal is open");
cy.wait("@listAlerts");
+ selectScheduleTime();
modal().within(() => {
cy.findByRole("heading", { name: "New alert" }).should("be.visible");
cy.button("Done").click();
@@ -155,6 +156,7 @@ describe("scenarios > embedding-sdk > interactive-question", () => {
});
popover().findByRole("option", { name: "weekly" }).click();
+ selectScheduleTime();
modal().within(() => {
cy.button("Save changes").click();
cy.findByRole("heading", { name: "Edit alerts" }).should("be.visible");
diff --git a/e2e/test-component/scenarios/embedding-sdk/static-question.cy.spec.tsx b/e2e/test-component/scenarios/embedding-sdk/static-question.cy.spec.tsx
index f84ae2e785d..baecade46f3 100644
--- a/e2e/test-component/scenarios/embedding-sdk/static-question.cy.spec.tsx
+++ b/e2e/test-component/scenarios/embedding-sdk/static-question.cy.spec.tsx
@@ -8,7 +8,12 @@ import {
import { SAMPLE_DB_ID } from "e2e/support/cypress_data";
import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";
-import { createQuestion, modal, popover } from "e2e/support/helpers";
+import {
+ createQuestion,
+ modal,
+ popover,
+ selectScheduleTime,
+} from "e2e/support/helpers";
import { getSdkRoot } from "e2e/support/helpers/e2e-embedding-sdk-helpers";
import {
DEFAULT_SDK_AUTH_PROVIDER_CONFIG,
@@ -217,6 +222,7 @@ describe("scenarios > embedding-sdk > static-question", () => {
cy.log("alerts modal is open");
cy.wait("@listAlerts");
+ selectScheduleTime();
modal().within(() => {
cy.findByRole("heading", { name: "New alert" }).should("be.visible");
cy.button("Done").click();
@@ -238,6 +244,7 @@ describe("scenarios > embedding-sdk > static-question", () => {
});
popover().findByRole("option", { name: "weekly" }).click();
+ selectScheduleTime();
modal().within(() => {
cy.button("Save changes").click();
cy.findByRole("heading", { name: "Edit alerts" }).should("be.visible");
diff --git a/e2e/test/scenarios/embedding/sdk-iframe-embedding/embed-options.cy.spec.ts b/e2e/test/scenarios/embedding/sdk-iframe-embedding/embed-options.cy.spec.ts
index 600ef62b4a2..1e050179508 100644
--- a/e2e/test/scenarios/embedding/sdk-iframe-embedding/embed-options.cy.spec.ts
+++ b/e2e/test/scenarios/embedding/sdk-iframe-embedding/embed-options.cy.spec.ts
@@ -118,6 +118,7 @@ describe("EE", () => {
});
H.popover().findByRole("option", { name: "daily" }).click();
+ H.selectScheduleTime();
cy.findByRole("button", { name: "Done" }).click();
dashboardSidebar().within(() => {
diff --git a/e2e/test/scenarios/metrics/metric-page.cy.spec.ts b/e2e/test/scenarios/metrics/metric-page.cy.spec.ts
index f3945cac746..c89ef89475b 100644
--- a/e2e/test/scenarios/metrics/metric-page.cy.spec.ts
+++ b/e2e/test/scenarios/metrics/metric-page.cy.spec.ts
@@ -208,6 +208,7 @@ describe("scenarios > metrics > metric page", () => {
H.addNotificationHandlerChannel("Bar Hook");
+ H.selectScheduleTime();
cy.findByRole("button", { name: "Done" }).click();
cy.wait("@createAlert").then(({ response }) => {
diff --git a/e2e/test/scenarios/question/saved.cy.spec.js b/e2e/test/scenarios/question/saved.cy.spec.js
index ddbf3446d3b..8772a8eab19 100644
--- a/e2e/test/scenarios/question/saved.cy.spec.js
+++ b/e2e/test/scenarios/question/saved.cy.spec.js
@@ -640,6 +640,7 @@ describe(
H.addNotificationHandlerChannel(secondWebhookName, {
hasNoChannelsAdded: true,
});
+ H.selectScheduleTime();
H.modal().button("Done").click();
cy.findByLabelText("Move, trash, and more…").click();
diff --git a/e2e/test/scenarios/sharing/alert/alert-permissions.cy.spec.js b/e2e/test/scenarios/sharing/alert/alert-permissions.cy.spec.js
index 82667c873bd..7489adca222 100644
--- a/e2e/test/scenarios/sharing/alert/alert-permissions.cy.spec.js
+++ b/e2e/test/scenarios/sharing/alert/alert-permissions.cy.spec.js
@@ -58,6 +58,7 @@ describe("scenarios > alert > alert permissions", { tags: "@external" }, () => {
H.modal().findByTestId("select-frequency").click();
H.popover().findByText("weekly").click();
+ H.selectScheduleTime();
H.modal().button("Save changes").click();
// Check that changes stuck
@@ -137,6 +138,7 @@ describe("scenarios > alert > alert permissions", { tags: "@external" }, () => {
cy.findByTestId("select-frequency").click();
});
H.popover().findByText("weekly").click();
+ H.selectScheduleTime();
H.modal().button("Save changes").click();
@@ -163,6 +165,7 @@ function createBasicAlert({ includeNormal } = {}) {
.type(`${H.getFullName(normal)}{enter}`);
}
+ H.selectScheduleTime();
cy.findByText("Done").click();
cy.findByText("New alert").should("not.exist");
}
diff --git a/e2e/test/scenarios/sharing/alert/alert-types.cy.spec.js b/e2e/test/scenarios/sharing/alert/alert-types.cy.spec.js
index 424a9176b94..8ce05a0aa3f 100644
--- a/e2e/test/scenarios/sharing/alert/alert-types.cy.spec.js
+++ b/e2e/test/scenarios/sharing/alert/alert-types.cy.spec.js
@@ -59,6 +59,7 @@ describe("scenarios > alert > types", { tags: "@external" }, () => {
H.popover().findByText("Create an alert").click();
cy.wait("@channel");
+ H.selectScheduleTime();
H.modal().within(() => {
cy.findByText("New alert").should("be.visible");
@@ -103,6 +104,7 @@ describe("scenarios > alert > types", { tags: "@external" }, () => {
cy.findByText("When results go above the goal").click();
});
+ H.selectScheduleTime();
H.modal().within(() => {
cy.findByLabelText("Delete this Alert after it's triggered").click();
@@ -123,6 +125,7 @@ describe("scenarios > alert > types", { tags: "@external" }, () => {
H.popover().findByText("Create an alert").click();
cy.wait("@channel");
+ H.selectScheduleTime();
H.modal().within(() => {
cy.findByText("New alert").should("be.visible");
diff --git a/e2e/test/scenarios/sharing/alert/alert.cy.spec.js b/e2e/test/scenarios/sharing/alert/alert.cy.spec.js
index 4eeb4a691f3..992a5e188b3 100644
--- a/e2e/test/scenarios/sharing/alert/alert.cy.spec.js
+++ b/e2e/test/scenarios/sharing/alert/alert.cy.spec.js
@@ -80,6 +80,7 @@ describe("scenarios > alert", () => {
H.addNotificationHandlerChannel("Bar Hook");
+ H.selectScheduleTime();
cy.findByRole("button", { name: "Done" }).click();
H.notificationList().findByText("Your alert is all set up.");
@@ -138,6 +139,7 @@ describe("scenarios > alert", () => {
cy.findByLabelText("Move, duplicate, and more…").click();
H.popover().findByText("Create an alert").click();
+ H.selectScheduleTime();
H.modal().button("Done").click();
cy.findByLabelText("Move, duplicate, and more…").click();
@@ -187,6 +189,7 @@ describe("scenarios > alert", () => {
cy.findByLabelText("Move, trash, and more…").click();
H.popover().findByText("Create an alert").click();
+ H.selectScheduleTime();
H.modal().within(() => {
cy.findByText("New alert").should("be.visible");
@@ -218,6 +221,7 @@ describe("scenarios > alert", () => {
cy.findByLabelText("Move, trash, and more…").click();
H.popover().findByText("Create an alert").click();
+ H.selectScheduleTime();
H.modal().within(() => {
cy.findByText("New alert").should("be.visible");
diff --git a/e2e/test/scenarios/sharing/alert/email-alert.cy.spec.js b/e2e/test/scenarios/sharing/alert/email-alert.cy.spec.js
index 8ab97778c37..53526f4d15e 100644
--- a/e2e/test/scenarios/sharing/alert/email-alert.cy.spec.js
+++ b/e2e/test/scenarios/sharing/alert/email-alert.cy.spec.js
@@ -38,6 +38,7 @@ describe("scenarios > alert > email_alert", { tags: "@external" }, () => {
cy.findByText("Slack").should("not.exist");
});
+ H.selectScheduleTime();
cy.button("Done").click();
cy.wait("@saveAlert").then(({ response: { body } }) => {
@@ -46,6 +47,19 @@ describe("scenarios > alert > email_alert", { tags: "@external" }, () => {
});
});
+ it("should not claim a schedule when sending a one-off alert", () => {
+ createQuestionAndOpenAlert("One-off alert");
+
+ H.sendAlertAndVisitIt();
+
+ cy.get("table.header")
+ .first()
+ .within(() => {
+ cy.findByText("One-off alert").should("be.visible");
+ cy.findByText(/Run daily at/).should("not.exist");
+ });
+ });
+
it("should respect email alerts toggled off (metabase#12349)", () => {
H.updateSetting("report-timezone", "America/New_York");
@@ -69,6 +83,7 @@ describe("scenarios > alert > email_alert", { tags: "@external" }, () => {
H.removeNotificationHandlerChannel("Email");
+ H.selectScheduleTime();
H.modal().within(() => {
cy.button("Done").click();
});
@@ -104,6 +119,7 @@ describe("scenarios > alert > email_alert", { tags: "@external" }, () => {
.click();
H.popover().findByText("#work").click();
+ H.selectScheduleTime();
H.modal().within(() => {
cy.button("Done").click();
});
@@ -164,6 +180,7 @@ describe("scenarios > alert > email_alert", { tags: "@external" }, () => {
.should("have.attr", "value", "weekly")
.should("have.attr", "aria-selected", "false")
.click();
+ H.selectScheduleTime();
cy.button("Save changes").click();
cy.log("Check that /api/card has still only been called once");
@@ -225,10 +242,11 @@ function saveAlert() {
cy.findByLabelText("Move, duplicate, and more…").click();
H.popover().findByText("Create an alert").click();
+ H.selectScheduleTime();
H.modal().button("Done").click();
}
-function sendTestAlertForQuestion(name) {
+function createQuestionAndOpenAlert(name) {
H.createNativeQuestion(
{
name,
@@ -239,6 +257,11 @@ function sendTestAlertForQuestion(name) {
cy.findByLabelText("Move, trash, and more…").click();
H.popover().findByText("Create an alert").click();
+}
+
+function sendTestAlertForQuestion(name) {
+ createQuestionAndOpenAlert(name);
+ H.selectScheduleTime();
H.sendAlertAndVisitIt();
cy.findAllByRole("link").filter(`:contains(${name})`).should("be.visible");
}
diff --git a/e2e/test/scenarios/sharing/subscriptions.cy.spec.js b/e2e/test/scenarios/sharing/subscriptions.cy.spec.js
index daa7c0625c6..20c1344ce53 100644
--- a/e2e/test/scenarios/sharing/subscriptions.cy.spec.js
+++ b/e2e/test/scenarios/sharing/subscriptions.cy.spec.js
@@ -129,6 +129,19 @@ describe("scenarios > dashboard > subscriptions", () => {
cy.findByText("Emailed hourly");
});
+ it("should still send a one-off email after the frequency change clears the time", () => {
+ assignRecipient();
+
+ cy.findByTestId("select-frequency").click();
+ H.popover().findByText("weekly").click();
+
+ H.sidebar().button("Done").should("be.disabled");
+ H.sidebar().button("Send email now").should("be.enabled");
+
+ H.clickSend();
+ H.getInbox(1).its("body").should("have.length", 1);
+ });
+
it("should not add a recipient when Escape is pressed (metabase#24629)", () => {
openDashboardSubscriptions(ORDERS_DASHBOARD_ID);
@@ -409,6 +422,7 @@ describe("scenarios > dashboard > subscriptions", () => {
cy.findByTestId("select-frame").click();
H.popover().findByText("first").click();
+ H.selectScheduleTime();
clickButton("Done");
// Implicit assertion (word mustn't contain string "null")
H.sidebar().findByText(/^Emailed monthly on the first (?!null)/);
diff --git a/frontend/src/embedding-sdk-bundle/components/public/question/shared-tests/alert-modal.spec.ts b/frontend/src/embedding-sdk-bundle/components/public/question/shared-tests/alert-modal.spec.ts
index ce1065b7cbd..f6a0e48fca0 100644
--- a/frontend/src/embedding-sdk-bundle/components/public/question/shared-tests/alert-modal.spec.ts
+++ b/frontend/src/embedding-sdk-bundle/components/public/question/shared-tests/alert-modal.spec.ts
@@ -83,6 +83,10 @@ export function addAlertModalTests(
withinModal.queryByText("Where do you want to send the results?"),
).not.toBeInTheDocument();
expect(withinModal.getByText("More options")).toBeVisible();
+
+ await userEvent.click(withinModal.getByTestId("select-time"));
+ await userEvent.click(screen.getByRole("option", { name: "8:00" }));
+
await userEvent.click(withinModal.getByRole("button", { name: "Done" }));
const createNotificationRequest = (await findRequests("POST")).find(
diff --git a/frontend/src/metabase-types/api/settings.ts b/frontend/src/metabase-types/api/settings.ts
index fcf998582e4..2e5dc5056dd 100644
--- a/frontend/src/metabase-types/api/settings.ts
+++ b/frontend/src/metabase-types/api/settings.ts
@@ -164,22 +164,14 @@ export interface EngineSourceContact {
}
export interface ScheduleSettings {
- schedule_type?: ScheduleType | null;
+ schedule_type: ScheduleType;
schedule_day?: ScheduleDayType | null;
schedule_frame?: ScheduleFrameType | null;
schedule_hour?: number | null;
schedule_minute?: number | null;
}
-export type ScheduleType =
- | "every_n_minutes"
- | "hourly"
- | "daily"
- | "weekly"
- | "monthly"
- // 'cron' type implies usage of more complex expressions represented
- // by raw cron string.
- | "cron";
+export type ScheduleType = "hourly" | "daily" | "weekly" | "monthly";
export type ScheduleDayType =
| "sun"
diff --git a/frontend/src/metabase/admin/performance/components/StrategyForm.tsx b/frontend/src/metabase/admin/performance/components/StrategyForm.tsx
index e1231b602a5..e283b61899b 100644
--- a/frontend/src/metabase/admin/performance/components/StrategyForm.tsx
+++ b/frontend/src/metabase/admin/performance/components/StrategyForm.tsx
@@ -7,7 +7,8 @@ import _ from "underscore";
import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";
import { Schedule } from "metabase/common/components/Schedule/Schedule";
-import { cronToScheduleSettings } from "metabase/common/components/Schedule/cron";
+import { cronToBuilderValue } from "metabase/common/components/Schedule/cron";
+import type { ScheduleChangeEvent } from "metabase/common/components/Schedule/types";
import type { FormTextInputProps } from "metabase/forms";
import {
Form,
@@ -41,7 +42,7 @@ import type {
} from "metabase-types/api";
import { CacheDurationUnit } from "metabase-types/api";
-import { defaultCronSchedule, rootId } from "../constants/simple";
+import { rootId } from "../constants/simple";
import { useIsFormPending } from "../hooks/useIsFormPending";
import {
getDefaultValueForField,
@@ -405,13 +406,15 @@ const ScheduleStrategyFormFields = ({
}) => {
const { values, setFieldValue } = useFormikContext<ScheduleStrategy>();
const { schedule: scheduleInCronFormat } = values;
- const initialSchedule = cronToScheduleSettings(scheduleInCronFormat);
+ const initialSchedule = cronToBuilderValue(scheduleInCronFormat);
const timezone = useSelector((state) =>
getSetting(state, "report-timezone-short"),
);
const onScheduleChange = useCallback(
- (newCronSchedule: string) => {
- setFieldValue("schedule", newCronSchedule);
+ ({ cronString }: ScheduleChangeEvent) => {
+ if (cronString) {
+ setFieldValue("schedule", cronString);
+ }
},
[setFieldValue],
);
@@ -439,7 +442,7 @@ const ScheduleStrategyFormFields = ({
</Text>
</Stack>
<Schedule
- cronString={scheduleInCronFormat || defaultCronSchedule}
+ value={initialSchedule}
scheduleOptions={["hourly", "daily", "weekly", "monthly"]}
onScheduleChange={onScheduleChange}
verb={c("A verb in the imperative mood").t`Invalidate`}
diff --git a/frontend/src/metabase/admin/performance/constants/simple.ts b/frontend/src/metabase/admin/performance/constants/simple.ts
index bc7959e7ec6..4aec65a9e38 100644
--- a/frontend/src/metabase/admin/performance/constants/simple.ts
+++ b/frontend/src/metabase/admin/performance/constants/simple.ts
@@ -1,2 +1 @@
export const rootId = 0;
-export const defaultCronSchedule = "0 0 * * * ? *";
diff --git a/frontend/src/metabase/admin/performance/utils.tsx b/frontend/src/metabase/admin/performance/utils.tsx
index 27195802871..41cf72a3fd1 100644
--- a/frontend/src/metabase/admin/performance/utils.tsx
+++ b/frontend/src/metabase/admin/performance/utils.tsx
@@ -3,7 +3,7 @@ import { c } from "ttag";
import * as Yup from "yup";
import type { SchemaObjectDescription } from "yup/lib/schema";
-import { cronToScheduleSettings } from "metabase/common/components/Schedule/cron";
+import { cronToBuilderValue } from "metabase/common/components/Schedule/cron";
import { getScheduleStrings } from "metabase/common/components/Schedule/strings";
import {
PLUGIN_CACHING,
@@ -48,7 +48,7 @@ export const resolveSmoothly = async (
};
export const getFrequencyFromCron = (cron: string) => {
- const scheduleType = cronToScheduleSettings(cron)?.schedule_type;
+ const scheduleType = cronToBuilderValue(cron)?.schedule_type;
const { scheduleOptionNames } = getScheduleStrings();
return isNullOrUndefined(scheduleType)
? ""
diff --git a/frontend/src/metabase/common/components/Schedule/AutoWidthSelect.tsx b/frontend/src/metabase/common/components/Schedule/AutoWidthSelect.tsx
index a20d00c67a4..a33baddcc78 100644
--- a/frontend/src/metabase/common/components/Schedule/AutoWidthSelect.tsx
+++ b/frontend/src/metabase/common/components/Schedule/AutoWidthSelect.tsx
@@ -9,7 +9,7 @@ import type { FontStyle } from "metabase/utils/measure-text";
import { getLongestSelectLabel, measureTextWidthSafely } from "./utils";
/** A Select that is automatically sized to fit its largest option name */
-export const AutoWidthSelect = <Value extends string>({
+export const AutoWidthSelect = <Value extends string | null>({
style,
value,
...props
@@ -18,15 +18,15 @@ export const AutoWidthSelect = <Value extends string>({
getSetting(state, "application-font"),
);
const width = useMemo(() => {
+ const fontStyle = { family: fontFamily, ...style };
const longestLabel = getLongestSelectLabel(props.data, fontFamily);
- const width =
- measureTextWidthSafely(longestLabel, 50, {
- family: fontFamily,
- ...style,
- }) + 60;
+ const labelWidth = measureTextWidthSafely(longestLabel, 50, fontStyle);
+ const placeholderWidth = props.placeholder
+ ? measureTextWidthSafely(props.placeholder, 50, fontStyle)
+ : 0;
- return width;
- }, [props.data, style, fontFamily]);
+ return Math.max(labelWidth, placeholderWidth) + 60;
+ }, [props.data, props.placeholder, style, fontFamily]);
return (
<Select
styles={{
diff --git a/frontend/src/metabase/common/components/Schedule/Schedule.stories.tsx b/frontend/src/metabase/common/components/Schedule/Schedule.stories.tsx
index 342eba6744e..47076ee4b4d 100644
--- a/frontend/src/metabase/common/components/Schedule/Schedule.stories.tsx
+++ b/frontend/src/metabase/common/components/Schedule/Schedule.stories.tsx
@@ -10,9 +10,10 @@ import { LocaleProvider } from "metabase/embedding/LocaleProvider";
import { MetabaseReduxProvider } from "metabase/redux";
import type { State } from "metabase/redux/store";
import { createMockState } from "metabase/redux/store/mocks";
-import type { ScheduleSettings } from "metabase-types/api";
import { Schedule } from "./Schedule";
+import { cronToBuilderValue } from "./cron";
+import type { ScheduleValue } from "./types";
const storeInitialState = createMockState({
settings: mockSettings(),
@@ -38,7 +39,7 @@ export default {
const Template: StoryFn<typeof Schedule> = (args) => {
const [
{
- cronString,
+ value,
scheduleOptions = [
"every_n_minutes",
"hourly",
@@ -49,27 +50,21 @@ const Template: StoryFn<typeof Schedule> = (args) => {
timezone = "UTC",
locale = "en",
longVerb = false,
- isCustomSchedule = false,
},
updateArgs,
] = useArgs();
const verb = longVerb ? t`Clear cache for this dashboard` : t`Send`;
- const handleChange = (cronString: string, schedule: ScheduleSettings) =>
- updateArgs({
- cronString,
- isCustomSchedule: schedule.schedule_type === "cron",
- });
+
return (
<LocaleProvider locale={locale}>
<Schedule
{...args}
verb={verb}
- cronString={cronString}
+ value={value}
scheduleOptions={scheduleOptions}
timezone={timezone}
- onScheduleChange={handleChange}
- isCustomSchedule={isCustomSchedule}
+ onScheduleChange={updateArgs}
/>
</LocaleProvider>
);
@@ -79,7 +74,7 @@ export const Default = {
render: Template,
args: {
- cronString: "0 0 9 * * ? *",
+ value: cronToBuilderValue("0 0 9 * * ? *"),
longVerb: false,
locale: "en",
},
@@ -88,7 +83,7 @@ export const Default = {
export const LongVerb = {
render: Template,
args: {
- cronString: "0 0 9 * * ? *",
+ value: cronToBuilderValue("0 0 9 * * ? *"),
longVerb: true,
locale: "en",
},
@@ -97,7 +92,7 @@ export const LongVerb = {
export const EveryNMinutes = {
render: Template,
args: {
- cronString: "0 0/10 * * * ? *",
+ value: cronToBuilderValue("0 0/10 * * * ? *"),
longVerb: false,
locale: "en",
},
@@ -106,7 +101,7 @@ export const EveryNMinutes = {
export const HourlyOnSpecificMinute = {
render: Template,
args: {
- cronString: "0 10 * * * ? *",
+ value: cronToBuilderValue("0 10 * * * ? *"),
longVerb: false,
locale: "en",
minutesOnHourPicker: true,
@@ -116,7 +111,7 @@ export const HourlyOnSpecificMinute = {
export const CustomSchedule = {
render: Template,
args: {
- cronString: "0 10 10 * * ? *",
+ value: { schedule_type: "cron", cron: "0 10 10 * * ? *" },
scheduleOptions: [
"every_n_minutes",
"hourly",
@@ -125,18 +120,14 @@ export const CustomSchedule = {
"monthly",
"cron",
],
- isCustomSchedule: true,
- renderScheduleDescription: (
- schedule: ScheduleSettings,
- cronString: string,
- ) => {
+ renderScheduleDescription: (value: ScheduleValue, cronString: string) => {
return (
<ul style={{ marginTop: "1rem" }}>
<li>
Demo of <code>renderScheduleDescription</code>:
</li>
<li>Cron String: {cronString}</li>
- <li>Schedule updated on blur: {JSON.stringify(schedule)}</li>
+ <li>Schedule updated on blur: {JSON.stringify(value)}</li>
</ul>
);
},
diff --git a/frontend/src/metabase/common/components/Schedule/Schedule.tsx b/frontend/src/metabase/common/components/Schedule/Schedule.tsx
index f0f3a53d9b6..0b2022e0db1 100644
--- a/frontend/src/metabase/common/components/Schedule/Schedule.tsx
+++ b/frontend/src/metabase/common/components/Schedule/Schedule.tsx
@@ -2,13 +2,11 @@ import cx from "classnames";
import { type HTMLAttributes, useCallback, useMemo, useState } from "react";
import { match } from "ts-pattern";
import { c } from "ttag";
-import _ from "underscore";
import { CronExpressionInput } from "metabase/common/components/CronExpressioInput";
import { Box, Flex, type FlexProps } from "metabase/ui";
import { formatCronExpressionForUI } from "metabase/utils/cron";
-import { removeNullAndUndefinedValues } from "metabase/utils/types";
-import type { ScheduleSettings, ScheduleType } from "metabase-types/api";
+import type { ScheduleSettings } from "metabase-types/api";
import {
GROUP_ATTRIBUTES,
@@ -23,120 +21,139 @@ import {
SelectWeekday,
SelectWeekdayOfMonth,
} from "./components";
-import { cronToScheduleSettings, scheduleSettingsToCron } from "./cron";
+import { scheduleValueToCron, toScheduleBuilderValue } from "./cron";
import { byTheMinuteIntervals } from "./strings";
-import type { UpdateSchedule } from "./types";
-import { getScheduleDefaults } from "./utils";
+import type {
+ ScheduleBuilderValue,
+ ScheduleChangeEvent,
+ ScheduleValue,
+ ScheduleValueType,
+ UpdateSchedule,
+} from "./types";
+import { isScheduleCronValue } from "./types";
+import {
+ type GetScheduleDefaults,
+ clearDayForMidFrame,
+ getScheduleDefaults,
+ isScheduleComplete,
+ normalizeScheduleValue,
+ resetScheduleToTypeDefaults,
+} from "./utils";
export interface ScheduleProps {
className?: string;
- cronString: string;
- scheduleOptions: ScheduleType[];
- onScheduleChange: (
- nextCronString: string,
- nextSchedule: ScheduleSettings,
- ) => void;
+ value: ScheduleValue;
+ scheduleOptions: ScheduleValueType[];
+ onScheduleChange: (event: ScheduleChangeEvent) => void;
timezone?: string;
verb?: string;
minutesOnHourPicker?: boolean;
+ getDefaults?: GetScheduleDefaults;
labelAlignment?: "compact" | "left";
layout?: "vertical" | "horizontal";
- isCustomSchedule?: boolean;
renderScheduleDescription?: (
- schedule: ScheduleSettings,
- cronString: string,
+ value: ScheduleValue,
+ cronInputValue: string,
) => JSX.Element | string | null;
}
export const Schedule = ({
className,
- cronString: initialCronString,
+ value,
scheduleOptions,
timezone,
verb,
minutesOnHourPicker,
+ getDefaults = getScheduleDefaults,
onScheduleChange,
labelAlignment = "compact",
layout = "vertical",
- isCustomSchedule,
renderScheduleDescription,
...flexProps
}: ScheduleProps & FlexProps & HTMLAttributes<HTMLDivElement>) => {
- const [internalCronString, setInternalCronString] = useState(() =>
- formatCronExpressionForUI(initialCronString),
+ const normalizedValue = useMemo<ScheduleValue>(
+ () => normalizeScheduleValue(value, getDefaults),
+ [value, getDefaults],
+ );
+ const [cronInputValue, setCronInputValue] = useState(() =>
+ formatCronExpressionForUI(scheduleValueToCron(normalizedValue)),
);
- const schedule = useMemo<ScheduleSettings>(() => {
- return (
- cronToScheduleSettings(initialCronString, isCustomSchedule) ?? {
- schedule_type: "hourly",
- schedule_minute: 0,
- }
- );
- }, [initialCronString, isCustomSchedule]);
-
- const updateSchedule: UpdateSchedule = useCallback(
- (
- updatedField: keyof ScheduleSettings,
- newValue: ScheduleSettings[typeof updatedField],
- ) => {
- let newSchedule: ScheduleSettings = {
- ...schedule,
- [updatedField]: newValue,
- };
- const defaults = getScheduleDefaults(newSchedule);
- if (updatedField === "schedule_type") {
- // When a new schedule type is selected, use the default values for that type
- newSchedule = {
- // Unjustified type cast. FIXME
- schedule_type: newValue as ScheduleType,
- ...defaults,
- };
- if (newValue === "cron") {
- setInternalCronString(formatCronExpressionForUI(initialCronString));
- }
- } else {
- newSchedule = _.defaults(
- removeNullAndUndefinedValues(newSchedule),
- defaults,
- );
- }
+ const emitChange = useCallback(
+ (nextValue: ScheduleValue) => {
+ onScheduleChange({
+ value: nextValue,
+ cronString: isScheduleComplete(nextValue)
+ ? scheduleValueToCron(nextValue)
+ : null,
+ });
+ },
+ [onScheduleChange],
+ );
- // when the monthly schedule frame is the 15th, clear out the schedule_day
- if (newSchedule.schedule_frame === "mid") {
- newSchedule.schedule_day = null;
+ const updateScheduleType = useCallback(
+ (scheduleType: ScheduleValueType) => {
+ if (scheduleType === "cron") {
+ const cron = scheduleValueToCron(normalizedValue);
+ setCronInputValue(formatCronExpressionForUI(cron));
+ emitChange({ schedule_type: "cron", cron });
+ return;
}
- const newCronString = scheduleSettingsToCron(newSchedule);
- onScheduleChange(newCronString, newSchedule);
+ emitChange(
+ resetScheduleToTypeDefaults(
+ toScheduleBuilderValue(normalizedValue),
+ scheduleType,
+ getDefaults,
+ ),
+ );
},
- [initialCronString, onScheduleChange, schedule],
+ [emitChange, getDefaults, normalizedValue],
);
- const renderedSchedule = useMemo(() => {
- // Merge default values into the schedule
- const scheduleWithDefaults: ScheduleSettings = _.defaults(
- schedule,
- getScheduleDefaults(schedule),
- );
+ const createUpdateSchedule = useCallback(
+ (schedule: ScheduleBuilderValue): UpdateSchedule =>
+ (
+ updatedField: keyof ScheduleSettings,
+ newValue: ScheduleSettings[typeof updatedField],
+ ) => {
+ const nextValue: ScheduleBuilderValue = {
+ ...schedule,
+ [updatedField]: newValue,
+ };
- const {
- schedule_type,
- schedule_frame,
- schedule_day,
- schedule_hour,
- schedule_minute,
- } = scheduleWithDefaults;
+ emitChange(clearDayForMidFrame(nextValue));
+ },
+ [emitChange],
+ );
+ const renderedSchedule = useMemo(() => {
const selectFrequency = (
<SelectFrequency
key="frequency"
- updateSchedule={updateSchedule}
- scheduleType={schedule_type}
+ scheduleType={normalizedValue.schedule_type}
+ onScheduleTypeChange={updateScheduleType}
scheduleOptions={scheduleOptions}
/>
);
+ if (isScheduleCronValue(normalizedValue)) {
+ const selectCron = (
+ <CronExpressionInput
+ data-group={GROUP_ATTRIBUTES.separate}
+ key="cron"
+ value={cronInputValue}
+ onChange={setCronInputValue}
+ onBlurChange={(cron) => emitChange({ schedule_type: "cron", cron })}
+ />
+ );
+ return [verb, selectFrequency, selectCron];
+ }
+
+ const { schedule_frame, schedule_day, schedule_hour, schedule_minute } =
+ normalizedValue;
+ const updateSchedule = createUpdateSchedule(normalizedValue);
+
const selectMinute = (
<SelectMinute
key="minute"
@@ -187,23 +204,7 @@ export const Schedule = ({
/>
);
- const selectCron = (
- <CronExpressionInput
- data-group={GROUP_ATTRIBUTES.separate}
- key="cron"
- value={internalCronString}
- onChange={(value: string) => {
- setInternalCronString(value);
- }}
- onBlurChange={(value) =>
- onScheduleChange(value, {
- schedule_type: "cron",
- })
- }
- />
- );
-
- return match(schedule_type)
+ return match(normalizedValue.schedule_type)
.with("every_n_minutes", () => {
// "Minute" is registered as a plural msgid elsewhere; give this row's
// singular its own context so it's a distinct key (no extraction clash).
@@ -260,24 +261,22 @@ export const Schedule = ({
selectWeekdayOfMonth
} at ${selectTime}`,
)
- .with("cron", () => [verb, selectFrequency, selectCron])
- .with(null, () => null)
- .with(undefined, () => null)
.exhaustive();
}, [
minutesOnHourPicker,
- schedule,
+ normalizedValue,
scheduleOptions,
timezone,
- updateSchedule,
+ createUpdateSchedule,
+ updateScheduleType,
verb,
- internalCronString,
- onScheduleChange,
+ cronInputValue,
+ emitChange,
]);
const scheduleDescription = useMemo(() => {
- return renderScheduleDescription?.(schedule, internalCronString) || null;
- }, [renderScheduleDescription, schedule, internalCronString]);
+ return renderScheduleDescription?.(normalizedValue, cronInputValue) || null;
+ }, [renderScheduleDescription, normalizedValue, cronInputValue]);
return (
<Flex direction="column" gap="1rem" {...flexProps}>
diff --git a/frontend/src/metabase/common/components/Schedule/Schedule.unit.spec.tsx b/frontend/src/metabase/common/components/Schedule/Schedule.unit.spec.tsx
index 62bcc4ddc6c..cbf84321b90 100644
--- a/frontend/src/metabase/common/components/Schedule/Schedule.unit.spec.tsx
+++ b/frontend/src/metabase/common/components/Schedule/Schedule.unit.spec.tsx
@@ -2,12 +2,17 @@ import { within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { screen } from "__support__/ui";
+import { cronToBuilderValue } from "metabase/common/components/Schedule/cron";
import type { ScheduleComponentType } from "metabase/common/components/Schedule/strings";
import {
+ getDefaultsWithoutHour,
setup,
- setupHarness,
} from "metabase/common/components/Schedule/test-utils";
import { setLocalization } from "metabase/utils/i18n";
+import { checkNotNull } from "metabase/utils/types";
+
+const scheduleFromCron = (cronString: string) =>
+ checkNotNull(cronToBuilderValue(cronString));
const getInputValues = () => {
const inputs = screen.getAllByRole("textbox");
@@ -15,35 +20,45 @@ const getInputValues = () => {
return values;
};
+const expectAmPmToBe = (label: string) =>
+ expect(
+ within(screen.getByTestId("select-am-pm")).getByRole("radio", {
+ name: label,
+ }),
+ ).toBeChecked();
+
describe("Schedule", () => {
it("shows time when schedule is daily", () => {
- setup({ cronString: "0 0 8 * * ? *" });
+ setup({ value: scheduleFromCron("0 0 8 * * ? *") });
expect(getInputValues()).toEqual(["daily", "8:00"]);
});
it("shows minutes schedule is hourly and minutesOnHourPicker is true", () => {
- setup({ cronString: "0 0 * * * ? *", minutesOnHourPicker: true });
+ setup({
+ value: scheduleFromCron("0 0 * * * ? *"),
+ minutesOnHourPicker: true,
+ });
expect(getInputValues()).toEqual(["hourly", "0"]);
expect(screen.getByText("minutes past the hour")).toBeInTheDocument();
});
it("shows day and time when schedule is weekly", () => {
setup({
- cronString: "0 0 8 ? * 2 *",
+ value: scheduleFromCron("0 0 8 ? * 2 *"),
});
expect(getInputValues()).toEqual(["weekly", "Monday", "8:00"]);
});
it("shows first/last/mid value, day, and time when schedule is monthly", async () => {
setup({
- cronString: "0 0 8 ? * 2#1 *",
+ value: scheduleFromCron("0 0 8 ? * 2#1 *"),
});
expect(getInputValues()).toEqual(["monthly", "first", "Monday", "8:00"]);
});
it("shows 10 minutes by default for every_n_minutes schedule", () => {
setup({
- cronString: "0 0/10 * * * ? *",
+ value: scheduleFromCron("0 0/10 * * * ? *"),
});
expect(getInputValues()).toEqual(["by the minute", "10"]);
expect(screen.getByText("minutes")).toBeInTheDocument();
@@ -51,7 +66,7 @@ describe("Schedule", () => {
it("shows proper single noun for every_n_minutes schedule", () => {
setup({
- cronString: "0 0/1 * * * ? *",
+ value: scheduleFromCron("0 0/1 * * * ? *"),
});
expect(getInputValues()).toEqual(["by the minute", "1"]);
expect(screen.getByText("minute")).toBeInTheDocument();
@@ -59,7 +74,7 @@ describe("Schedule", () => {
it("shows proper plural noun for every_n_minutes schedule", () => {
setup({
- cronString: "0 0/5 * * * ? *",
+ value: scheduleFromCron("0 0/5 * * * ? *"),
});
expect(getInputValues()).toEqual(["by the minute", "5"]);
expect(screen.getByText("minutes")).toBeInTheDocument();
@@ -67,7 +82,7 @@ describe("Schedule", () => {
it("does not allow 0 minutes option for every_n_minutes schedule", async () => {
setup({
- cronString: "0 0/10 * * * ? *",
+ value: scheduleFromCron("0 0/10 * * * ? *"),
});
const minuteInput = screen.getByTestId("select-minute");
@@ -87,7 +102,7 @@ describe("Schedule", () => {
it("presents 0,1,2,3,4,5,6,10,15,20,30 for every_n_minutes schedule", async () => {
setup({
- cronString: "0 0/10 * * * ? *",
+ value: scheduleFromCron("0 0/10 * * * ? *"),
});
const minuteInput = screen.getByTestId("select-minute");
@@ -105,10 +120,7 @@ describe("Schedule", () => {
});
it("shows custom cron input", () => {
- setup({
- cronString: "0 0/5 * * * ? *",
- isCustomSchedule: true,
- });
+ setup({ value: { schedule_type: "cron", cron: "0 0/5 * * * ? *" } });
expect(getInputValues()).toEqual(["custom", "0/5 * * * ?"]);
});
@@ -177,7 +189,7 @@ describe("Schedule", () => {
],
],
])("renders the right fields for %s", (_label, cronString, expected) => {
- setup({ cronString });
+ setup({ value: scheduleFromCron(cronString) });
expected.forEach((label) => {
expect(screen.getByLabelText(label)).toBeInTheDocument();
});
@@ -383,6 +395,12 @@ describe("Schedule", () => {
{ frequency: "monthly" },
"0 0 8 1 * ? *",
],
+ [
+ "switch weekly to monthly drops the weekday",
+ "0 0 8 ? * 6 *",
+ { frequency: "monthly" },
+ "0 0 8 1 * ? *",
+ ],
[
"switch monthly to daily clears frame and weekday",
"0 0 8 ? * 2#1 *",
@@ -419,7 +437,9 @@ describe("Schedule", () => {
it.each(cases)(
"%s",
async (_label, initialCronString, clicks, expectedCron) => {
- const { onScheduleChange } = setupHarness({ initialCronString });
+ const { onScheduleChange } = setup({
+ value: scheduleFromCron(initialCronString),
+ });
// Unjustified type cast. FIXME
for (const entry of Object.entries(clicks) as [
ScheduleComponentType,
@@ -428,9 +448,66 @@ describe("Schedule", () => {
await pickField(entry[0], entry[1]);
}
expect(onScheduleChange).toHaveBeenCalled();
- expect(onScheduleChange.mock.calls.at(-1)?.[0]).toBe(expectedCron);
+ const lastEvent = checkNotNull(onScheduleChange.mock.calls.at(-1))[0];
+ expect(lastEvent.cronString).toBe(expectedCron);
},
);
+
+ it("keeps the day of the month a custom cron expression names", async () => {
+ setup({ value: { schedule_type: "cron", cron: "0 0 8 15 * ? *" } });
+
+ await pickField("frequency", "monthly");
+
+ expect(getInputValues()).toEqual(["monthly", "15th", "8:00"]);
+ });
+
+ describe("with defaults that supply no hour", () => {
+ it("leaves the time unpicked when coming from a custom cron expression", async () => {
+ const { onScheduleChange } = setup({
+ value: { schedule_type: "cron", cron: "0 0 15 1 * ? *" },
+ getDefaults: getDefaultsWithoutHour,
+ });
+
+ await pickField("frequency", "daily");
+
+ expect(screen.getByTestId("select-time")).toHaveValue("");
+ expectAmPmToBe("AM");
+ const lastEvent = checkNotNull(onScheduleChange.mock.calls.at(-1))[0];
+ expect(lastEvent.cronString).toBeNull();
+ });
+
+ it("unpicks the time the user had picked on the previous type", async () => {
+ const { onScheduleChange } = setup({
+ value: scheduleFromCron("0 0 20 * * ? *"),
+ getDefaults: getDefaultsWithoutHour,
+ });
+
+ await pickField("frequency", "weekly");
+
+ expect(screen.getByTestId("select-time")).toHaveValue("");
+ expectAmPmToBe("AM");
+ const lastEvent = checkNotNull(onScheduleChange.mock.calls.at(-1))[0];
+ expect(lastEvent.cronString).toBeNull();
+ });
+
+ it("lets the user pick AM/PM before the time, without picking a time for them", async () => {
+ const { onScheduleChange } = setup({
+ value: { schedule_type: "daily", schedule_hour: null },
+ getDefaults: getDefaultsWithoutHour,
+ });
+
+ await pickField("amPm", "PM");
+
+ expectAmPmToBe("PM");
+ expect(screen.getByTestId("select-time")).toHaveValue("");
+ expect(onScheduleChange).not.toHaveBeenCalled();
+
+ await pickField("time", "8:00");
+
+ const lastEvent = checkNotNull(onScheduleChange.mock.calls.at(-1))[0];
+ expect(lastEvent.cronString).toBe("0 0 20 * * ? *");
+ });
+ });
});
});
@@ -467,14 +544,14 @@ describe("Schedule i18n (metabase#77265)", () => {
it("renders the plural unit without leaking a {0} placeholder", () => {
setLocalization(HU_LOCALE);
- const { container } = setup({ cronString: "0 0/5 * * * ? *" });
+ const { container } = setup({ value: scheduleFromCron("0 0/5 * * * ? *") });
expect(container).not.toHaveTextContent(/\{\s*0\s*\}/);
expect(screen.getByText("percek")).toBeInTheDocument();
});
it("renders the singular unit without leaking a {0} placeholder", () => {
setLocalization(HU_LOCALE);
- const { container } = setup({ cronString: "0 0/1 * * * ? *" });
+ const { container } = setup({ value: scheduleFromCron("0 0/1 * * * ? *") });
expect(container).not.toHaveTextContent(/\{\s*0\s*\}/);
expect(screen.getByText("perc")).toBeInTheDocument();
});
diff --git a/frontend/src/metabase/common/components/Schedule/components.tsx b/frontend/src/metabase/common/components/Schedule/components.tsx
index 99dc515c56d..3634d17568f 100644
--- a/frontend/src/metabase/common/components/Schedule/components.tsx
+++ b/frontend/src/metabase/common/components/Schedule/components.tsx
@@ -1,20 +1,20 @@
-import { useMemo } from "react";
-import { t } from "ttag";
+import { useMemo, useState } from "react";
+import { c, t } from "ttag";
import { useSelector } from "metabase/redux";
import { getApplicationName } from "metabase/selectors/whitelabel";
import { Box, Group, SegmentedControl, Tooltip } from "metabase/ui";
import { capitalize } from "metabase/utils/formatting/strings";
import { has24HourModeSetting } from "metabase/utils/time-dayjs";
+import { isNotNull } from "metabase/utils/types";
import type {
ScheduleDayType,
ScheduleFrameType,
ScheduleSettings,
- ScheduleType,
} from "metabase-types/api";
import { AutoWidthSelect } from "./AutoWidthSelect";
-import { defaultHour } from "./constants";
+import { AM, PM } from "./constants";
import { hourTo24HourFormat, hourToTwelveHourFormat } from "./cron";
import {
type Weekday,
@@ -23,7 +23,7 @@ import {
getScheduleStrings,
minutes,
} from "./strings";
-import type { UpdateSchedule } from "./types";
+import type { AmPm, ScheduleValueType, UpdateSchedule } from "./types";
export type SelectFrameProps = {
schedule_frame: ScheduleSettings["schedule_frame"];
@@ -35,12 +35,12 @@ export type SelectFrameProps = {
* also known as the schedule 'type'. */
export const SelectFrequency = ({
scheduleType,
- updateSchedule,
+ onScheduleTypeChange,
scheduleOptions,
}: {
- scheduleType?: ScheduleType | null;
- updateSchedule: UpdateSchedule;
- scheduleOptions: ScheduleType[];
+ scheduleType: ScheduleValueType;
+ onScheduleTypeChange: (scheduleType: ScheduleValueType) => void;
+ scheduleOptions: ScheduleValueType[];
}) => {
const { scheduleOptionNames } = getScheduleStrings();
@@ -57,10 +57,8 @@ export const SelectFrequency = ({
return (
<AutoWidthSelect
display="flex"
- value={scheduleType ?? "daily"}
- onChange={(value: ScheduleType | null) =>
- updateSchedule("schedule_type", value)
- }
+ value={scheduleType}
+ onChange={onScheduleTypeChange}
data={scheduleTypeOptions}
aria-label={label}
data-testid="select-frequency"
@@ -98,18 +96,14 @@ export const SelectTime = ({
}) => {
const { amAndPM } = getScheduleStrings();
const isClock12Hour = !has24HourModeSetting();
- const hourIn24HourFormat =
- schedule_hour !== undefined &&
- schedule_hour !== null &&
- !isNaN(schedule_hour)
- ? schedule_hour
- : defaultHour;
- const hour = isClock12Hour
- ? hourToTwelveHourFormat(hourIn24HourFormat)
- : hourIn24HourFormat;
- const amPm = hourIn24HourFormat >= 12 ? 1 : 0;
- const hourIndex = isClock12Hour && hour === 12 ? 0 : hour;
- const value = hourIndex === 0 && isClock12Hour ? "12" : hourIndex.toString();
+ const [pendingAmPm, setPendingAmPm] = useState<AmPm>(AM);
+ const hour24 =
+ isNotNull(schedule_hour) && !isNaN(schedule_hour) ? schedule_hour : null;
+ const hour =
+ hour24 !== null && isClock12Hour ? hourToTwelveHourFormat(hour24) : hour24;
+ const isHourSet = hour !== null;
+ const value = isHourSet ? hour.toString() : null;
+ const amPm = hour24 === null ? pendingAmPm : hour24 >= 12 ? PM : AM;
const timeSelectLabel = useMemo(() => getScheduleComponentLabel("time"), []);
const amPmControlLabel = useMemo(() => getScheduleComponentLabel("amPm"), []);
const applicationName = useSelector(getApplicationName);
@@ -119,8 +113,13 @@ export const SelectTime = ({
{/* Select the hour */}
<AutoWidthSelect
value={value}
+ placeholder={c("Placeholder of a time picker with no time chosen yet")
+ .t`HH:MM`}
data={getHours()}
- onChange={(value: string) => {
+ onChange={(value: string | null) => {
+ if (value === null) {
+ return;
+ }
const num = Number(value);
updateSchedule(
"schedule_hour",
@@ -133,16 +132,19 @@ export const SelectTime = ({
{/* Choose between AM and PM */}
<Group gap="sm">
{isClock12Hour && (
- <SegmentedControl
+ <SegmentedControl<AmPm>
lh="1rem"
radius="sm"
- value={amPm.toString()}
- onChange={(value) =>
- updateSchedule(
- "schedule_hour",
- hourTo24HourFormat(hour, parseInt(value)),
- )
- }
+ value={amPm}
+ onChange={(value) => {
+ setPendingAmPm(value);
+ if (isHourSet) {
+ updateSchedule(
+ "schedule_hour",
+ hourTo24HourFormat(hour, value),
+ );
+ }
+ }}
data={amAndPM}
aria-label={amPmControlLabel}
data-testid="select-am-pm"
diff --git a/frontend/src/metabase/common/components/Schedule/constants.ts b/frontend/src/metabase/common/components/Schedule/constants.ts
index 12c7aac5f8a..9df552cdaa0 100644
--- a/frontend/src/metabase/common/components/Schedule/constants.ts
+++ b/frontend/src/metabase/common/components/Schedule/constants.ts
@@ -1,2 +1,5 @@
+export const AM = "am";
+export const PM = "pm";
+
export const defaultDay = "mon";
export const defaultHour = 8;
diff --git a/frontend/src/metabase/common/components/Schedule/cron.ts b/frontend/src/metabase/common/components/Schedule/cron.ts
index 551d211eb47..b1d9f98b159 100644
--- a/frontend/src/metabase/common/components/Schedule/cron.ts
+++ b/frontend/src/metabase/common/components/Schedule/cron.ts
@@ -4,13 +4,19 @@ import type {
ScheduleDayType,
ScheduleFrameType,
ScheduleSettings,
- ScheduleType,
} from "metabase-types/api";
+import { PM } from "./constants";
import { Cron, getScheduleStrings } from "./strings";
-
-const AM = 0;
-const PM = 1;
+import type {
+ AmPm,
+ CronString,
+ ScheduleBuilderType,
+ ScheduleBuilderValue,
+ ScheduleValue,
+} from "./types";
+import { isScheduleCronValue } from "./types";
+import { clearUnusedScheduleFields } from "./utils";
const everyToCronSyntax = (every: number | string) =>
`${Cron.EveryPrefix}${every}`;
@@ -39,35 +45,35 @@ const frameFromCronMap: Record<string, ScheduleFrameType> = {
const frameFromCron = (frameInCronFormat: string) =>
frameFromCronMap[frameInCronFormat];
-export const scheduleSettingsToCron = (settings: ScheduleSettings): string => {
+export const formatCron = (schedule: ScheduleBuilderValue): CronString => {
const second = "0";
const year = "*";
- let minute = settings.schedule_minute?.toString() ?? Cron.AllValues;
- const hour = settings.schedule_hour?.toString() ?? Cron.AllValues;
- let weekday = settings.schedule_day
- ? dayToCron(settings.schedule_day).toString()
+ let minute = schedule.schedule_minute?.toString() ?? Cron.AllValues;
+ const hour = schedule.schedule_hour?.toString() ?? Cron.AllValues;
+ let weekday = schedule.schedule_day
+ ? dayToCron(schedule.schedule_day).toString()
: Cron.NoSpecificValue;
const month = Cron.AllValues;
- let dayOfMonth: string = settings.schedule_day
+ let dayOfMonth: string = schedule.schedule_day
? Cron.NoSpecificValue
: Cron.AllValues;
- if (settings.schedule_type === "every_n_minutes") {
+ if (schedule.schedule_type === "every_n_minutes") {
minute = everyToCronSyntax(minute);
- } else if (settings.schedule_type === "monthly" && settings.schedule_frame) {
+ } else if (schedule.schedule_type === "monthly" && schedule.schedule_frame) {
// There are two kinds of monthly schedule:
// - weekday-based (e.g. "on the first Monday of the month")
// - date-based (e.g. "on the 15th of the month")
- if (settings.schedule_day) {
+ if (schedule.schedule_day) {
// Handle weekday-based monthly schedule
- const frameInCronFormat = frameToCron(settings.schedule_frame).replace(
+ const frameInCronFormat = frameToCron(schedule.schedule_frame).replace(
/^1$/,
"#1",
);
- const dayInCronFormat = dayToCron(settings.schedule_day);
+ const dayInCronFormat = dayToCron(schedule.schedule_day);
weekday = `${dayInCronFormat}${frameInCronFormat}`;
} else {
// Handle date-based monthly schedule
- dayOfMonth = frameToCron(settings.schedule_frame);
+ dayOfMonth = frameToCron(schedule.schedule_frame);
}
}
const cronExpression = [
@@ -82,29 +88,26 @@ export const scheduleSettingsToCron = (settings: ScheduleSettings): string => {
return cronExpression;
};
-const defaultSchedule: ScheduleSettings = {
+const defaultSchedule: ScheduleBuilderValue = {
schedule_type: "hourly",
schedule_minute: 0,
};
-export const defaultCron = scheduleSettingsToCron(defaultSchedule);
-
-export const toCronString = (schedule: ScheduleSettings): string => {
- const { schedule_type } = schedule;
- const keepDay = schedule_type === "weekly" || schedule_type === "monthly";
- const keepHour = keepDay || schedule_type === "daily";
- return scheduleSettingsToCron({
- ...schedule,
- schedule_day: keepDay ? schedule.schedule_day : null,
- schedule_frame: keepDay ? schedule.schedule_frame : null,
- schedule_hour: keepHour ? schedule.schedule_hour : null,
- });
+export const defaultCron = formatCron(defaultSchedule);
+
+export const toCronString = (schedule: ScheduleBuilderValue): CronString =>
+ formatCron(clearUnusedScheduleFields(schedule));
+
+export const scheduleValueToCron = (value: ScheduleValue): CronString => {
+ if (isScheduleCronValue(value)) {
+ return value.cron;
+ }
+
+ return toCronString(value);
};
-/** Returns null if we can't convert the cron expression to a ScheduleSettings object */
-export const cronToScheduleSettings_unmemoized = (
+export const cronToBuilderValue_unmemoized = (
cron: string | null | undefined,
- isCustomSchedule: boolean = false,
-): ScheduleSettings | null => {
+): ScheduleBuilderValue | null => {
if (!cron) {
return defaultSchedule;
}
@@ -120,13 +123,11 @@ export const cronToScheduleSettings_unmemoized = (
const [_second, minute, hour, dayOfMonth, month, weekday] = cron.split(" ");
- if (month !== Cron.AllValues && !isCustomSchedule) {
+ if (month !== Cron.AllValues) {
return null;
}
- let schedule_type: ScheduleType | undefined;
- if (isCustomSchedule) {
- schedule_type = "cron";
- } else if (dayOfMonth === Cron.AllValues) {
+ let schedule_type: ScheduleBuilderType | undefined;
+ if (dayOfMonth === Cron.AllValues) {
if (weekday === Cron.AllValues) {
if (hour === Cron.AllValues) {
schedule_type = isRepeatingEvery(minute) ? "every_n_minutes" : "hourly";
@@ -188,19 +189,18 @@ export const cronToScheduleSettings_unmemoized = (
schedule_frame,
};
};
-export const cronToScheduleSettings = memoize(
- cronToScheduleSettings_unmemoized,
- (cron, isCustomSchedule) => `${cron}_${isCustomSchedule}`,
-);
+export const cronToBuilderValue = memoize(cronToBuilderValue_unmemoized);
-const isValidAmPm = (amPm: number) => amPm === AM || amPm === PM;
+export const toScheduleBuilderValue = (
+ value: ScheduleValue,
+): ScheduleBuilderValue =>
+ isScheduleCronValue(value)
+ ? (cronToBuilderValue(value.cron) ?? defaultSchedule)
+ : value;
export const hourToTwelveHourFormat = (hour: number) => hour % 12 || 12;
-export const hourTo24HourFormat = (hour: number, amPm: number): number => {
- if (!isValidAmPm(amPm)) {
- amPm = AM;
- }
+export const hourTo24HourFormat = (hour: number, amPm: AmPm): number => {
const hour24 = amPm === PM ? (hour % 12) + 12 : hour % 12;
return hour24 === 24 ? 0 : hour24;
};
diff --git a/frontend/src/metabase/common/components/Schedule/cron.unit.spec.ts b/frontend/src/metabase/common/components/Schedule/cron.unit.spec.ts
index cd350c12b3d..4964c0311c6 100644
--- a/frontend/src/metabase/common/components/Schedule/cron.unit.spec.ts
+++ b/frontend/src/metabase/common/components/Schedule/cron.unit.spec.ts
@@ -1,94 +1,95 @@
-import type { ScheduleSettings } from "metabase-types/api";
-
+import { AM, PM } from "./constants";
import {
- cronToScheduleSettings,
+ cronToBuilderValue,
+ formatCron,
hourTo24HourFormat,
hourToTwelveHourFormat,
- scheduleSettingsToCron,
+ scheduleValueToCron,
toCronString,
} from "./cron";
+import type { ScheduleBuilderValue } from "./types";
-describe("scheduleSettingsToCron", () => {
+describe("formatCron", () => {
it("converts every_n_minutes schedule to cron", () => {
- const settings: ScheduleSettings = {
+ const settings: ScheduleBuilderValue = {
schedule_type: "every_n_minutes",
schedule_minute: 10,
schedule_hour: null,
};
- const cron = scheduleSettingsToCron(settings);
+ const cron = formatCron(settings);
expect(cron).toEqual("0 0/10 * * * ? *");
});
it("converts hourly schedule to cron", () => {
- const settings: ScheduleSettings = {
+ const settings: ScheduleBuilderValue = {
schedule_type: "hourly",
schedule_minute: 1,
schedule_hour: 1,
};
- const cron = scheduleSettingsToCron(settings);
+ const cron = formatCron(settings);
expect(cron).toEqual("0 1 1 * * ? *");
});
it("converts daily schedule to cron", () => {
- const settings: ScheduleSettings = {
+ const settings: ScheduleBuilderValue = {
schedule_type: "daily",
schedule_minute: 30,
schedule_hour: 14,
};
- const cron = scheduleSettingsToCron(settings);
+ const cron = formatCron(settings);
expect(cron).toEqual("0 30 14 * * ? *");
});
it("converts weekly schedule to cron", () => {
- const settings: ScheduleSettings = {
+ const settings: ScheduleBuilderValue = {
schedule_type: "weekly",
schedule_day: "mon",
schedule_minute: 0,
schedule_hour: 12,
};
- const cron = scheduleSettingsToCron(settings);
+ const cron = formatCron(settings);
expect(cron).toEqual("0 0 12 ? * 2 *");
});
it("converts 'first Wednesday of the month at 9:15am' to cron", () => {
- const settings: ScheduleSettings = {
+ const settings: ScheduleBuilderValue = {
schedule_type: "monthly",
schedule_day: "wed",
schedule_frame: "first",
schedule_minute: 15,
schedule_hour: 9,
};
- const cron = scheduleSettingsToCron(settings);
+ const cron = formatCron(settings);
expect(cron).toEqual("0 15 9 ? * 4#1 *");
});
it("converts 'last calendar day of the month' to cron", () => {
- const settings: ScheduleSettings = {
+ const settings: ScheduleBuilderValue = {
schedule_type: "monthly",
schedule_frame: "last",
schedule_minute: 45,
schedule_hour: 16,
};
- const cron = scheduleSettingsToCron(settings);
+ const cron = formatCron(settings);
expect(cron).toEqual("0 45 16 L * ? *");
});
it("converts 'monthly on the 15th' to cron", () => {
- const settings: ScheduleSettings = {
+ const settings: ScheduleBuilderValue = {
schedule_type: "monthly",
schedule_frame: "mid",
schedule_minute: 5,
schedule_hour: 23,
};
- const cron = scheduleSettingsToCron(settings);
+ const cron = formatCron(settings);
expect(cron).toEqual("0 5 23 15 * ? *");
});
it("missing minute and hour should default to wildcard", () => {
- const settings: ScheduleSettings = {
+ const settings: ScheduleBuilderValue = {
schedule_type: "daily",
};
- const cron = scheduleSettingsToCron(settings);
+ const cron = formatCron(settings);
expect(cron).toEqual("0 * * * * ? *");
});
});
@@ -149,118 +150,111 @@ describe("toCronString", () => {
});
});
-describe("cronToScheduleSettings", () => {
+describe("cronToBuilderValue", () => {
it("returns default schedule when input is null or undefined", () => {
const defaultSchedule = {
schedule_type: "hourly",
schedule_minute: 0,
};
- expect(cronToScheduleSettings(null)).toEqual(defaultSchedule);
- expect(cronToScheduleSettings(undefined)).toEqual(defaultSchedule);
+ expect(cronToBuilderValue(null)).toEqual(defaultSchedule);
+ expect(cronToBuilderValue(undefined)).toEqual(defaultSchedule);
});
it("returns null when month is specified in cron", () => {
const cron = "0 15 10 15 1 ?";
- expect(cronToScheduleSettings(cron)).toBeNull();
+ expect(cronToBuilderValue(cron)).toBeNull();
});
describe("schedule type determination", () => {
it('sets schedule type to "every_n_minutes" when minute is "0/15"', () => {
const cron = `0 0/15 * * * ?`;
- expect(cronToScheduleSettings(cron)?.schedule_type).toBe(
- "every_n_minutes",
- );
+ expect(cronToBuilderValue(cron)?.schedule_type).toBe("every_n_minutes");
});
it('sets schedule type to "hourly" when hour is "*" and both dayOfMonth and dayOfWeek are "*"', () => {
const cron = "0 30 * * * *";
- expect(cronToScheduleSettings(cron)?.schedule_type).toBe("hourly");
+ expect(cronToBuilderValue(cron)?.schedule_type).toBe("hourly");
});
it('sets schedule type to "daily" when dayOfMonth and dayOfWeek are "*", and hour is specified', () => {
const cron = "0 30 8 * * *";
- expect(cronToScheduleSettings(cron)?.schedule_type).toBe("daily");
+ expect(cronToBuilderValue(cron)?.schedule_type).toBe("daily");
});
it('sets schedule type to "weekly" when dayOfWeek is specified', () => {
const cron = "0 30 8 ? * 1";
- expect(cronToScheduleSettings(cron)?.schedule_type).toBe("weekly");
+ expect(cronToBuilderValue(cron)?.schedule_type).toBe("weekly");
});
it('sets schedule type to "monthly" when dayOfMonth is specific', () => {
const cron = "0 30 8 15 * ?";
- expect(cronToScheduleSettings(cron)?.schedule_type).toBe("monthly");
- });
-
- it('sets schedule type to "cron" when isCustomSchedule is true', () => {
- const cron = "0 30 8 15 * ?";
- expect(cronToScheduleSettings(cron, true)?.schedule_type).toBe("cron");
+ expect(cronToBuilderValue(cron)?.schedule_type).toBe("monthly");
});
});
describe("monthly schedule determination", () => {
it('sets schedule frame to "mid" when dayOfMonth is "15"', () => {
const cron = "0 30 8 15 * ?";
- expect(cronToScheduleSettings(cron)?.schedule_frame).toBe("mid");
+ expect(cronToBuilderValue(cron)?.schedule_frame).toBe("mid");
});
it('sets schedule frame to "first" when dayOfMonth is "1"', () => {
const cron = "0 30 8 1 * ?";
- expect(cronToScheduleSettings(cron)?.schedule_frame).toBe("first");
+ expect(cronToBuilderValue(cron)?.schedule_frame).toBe("first");
});
it('sets schedule frame to "last" when dayOfMonth is "L"', () => {
const cron = "0 30 8 L * ?";
- expect(cronToScheduleSettings(cron)?.schedule_frame).toBe("last");
+ expect(cronToBuilderValue(cron)?.schedule_frame).toBe("last");
});
});
describe("weekly schedule determination", () => {
it('sets schedule_day to "sun" when dayOfWeek is 1', () => {
const cron = "0 30 8 ? * 1";
- expect(cronToScheduleSettings(cron)?.schedule_day).toBe("sun");
+ expect(cronToBuilderValue(cron)?.schedule_day).toBe("sun");
});
it('sets schedule_day to "mon" when dayOfWeek is 2', () => {
const cron = "0 30 8 ? * 2";
- expect(cronToScheduleSettings(cron)?.schedule_day).toBe("mon");
+ expect(cronToBuilderValue(cron)?.schedule_day).toBe("mon");
});
it('sets schedule_day to "tue" when dayOfWeek is 3', () => {
const cron = "0 30 8 ? * 3";
- expect(cronToScheduleSettings(cron)?.schedule_day).toBe("tue");
+ expect(cronToBuilderValue(cron)?.schedule_day).toBe("tue");
});
it('sets schedule_day to "wed" when dayOfWeek is 4', () => {
const cron = "0 30 8 ? * 4";
- expect(cronToScheduleSettings(cron)?.schedule_day).toBe("wed");
+ expect(cronToBuilderValue(cron)?.schedule_day).toBe("wed");
});
it('sets schedule_day to "thu" when dayOfWeek is 5', () => {
const cron = "0 30 8 ? * 5";
- expect(cronToScheduleSettings(cron)?.schedule_day).toBe("thu");
+ expect(cronToBuilderValue(cron)?.schedule_day).toBe("thu");
});
it('sets schedule_day to "fri" when dayOfWeek is 6', () => {
const cron = "0 30 8 ? * 6";
- expect(cronToScheduleSettings(cron)?.schedule_day).toBe("fri");
+ expect(cronToBuilderValue(cron)?.schedule_day).toBe("fri");
});
it('sets schedule_day to "sat" when dayOfWeek is 7', () => {
const cron = "0 30 8 ? * 7";
- expect(cronToScheduleSettings(cron)?.schedule_day).toBe("sat");
+ expect(cronToBuilderValue(cron)?.schedule_day).toBe("sat");
});
it('sets schedule_day to undefined if dayOfWeek is "?"', () => {
const cron = "0 30 8 ? * ?";
- expect(cronToScheduleSettings(cron)?.schedule_day).toBeUndefined();
+ expect(cronToBuilderValue(cron)?.schedule_day).toBeUndefined();
});
});
describe("hours and minutes extraction", () => {
it("correctly extracts the hour and minute from the cron", () => {
const cron = "0 20 3 * * *";
- const result = cronToScheduleSettings(cron);
+ const result = cronToBuilderValue(cron);
expect(result).toEqual(
expect.objectContaining({
schedule_minute: 20,
@@ -273,7 +267,7 @@ describe("cronToScheduleSettings", () => {
describe("every n minutes schedule determination", () => {
it('sets schedule type to "every_n_minutes" when minute is "0/15"', () => {
const cron = `0 0/15 * * * ?`;
- expect(cronToScheduleSettings(cron)).toEqual(
+ expect(cronToBuilderValue(cron)).toEqual(
expect.objectContaining({
schedule_type: "every_n_minutes",
schedule_minute: 15,
@@ -286,7 +280,7 @@ describe("cronToScheduleSettings", () => {
describe("specific cron strings", () => {
it("converts 0 0 22 ? * 2L correctly", () => {
const cron = "0 0 22 ? * 2L";
- expect(cronToScheduleSettings(cron)).toEqual({
+ expect(cronToBuilderValue(cron)).toEqual({
schedule_type: "monthly",
schedule_minute: 0,
schedule_hour: 22,
@@ -297,7 +291,7 @@ describe("cronToScheduleSettings", () => {
it("converts 0 0 6 ? * 6#1 correctly", () => {
const cron = "0 0 6 ? * 6#1";
- expect(cronToScheduleSettings(cron)).toEqual({
+ expect(cronToBuilderValue(cron)).toEqual({
schedule_type: "monthly",
schedule_minute: 0,
schedule_hour: 6,
@@ -326,48 +320,58 @@ describe("hourToTwelveHourFormat", () => {
describe("hourTo24HourFormat", () => {
// Test AM cases
it("converts 12 AM to 0", () => {
- expect(hourTo24HourFormat(12, 0)).toBe(0);
+ expect(hourTo24HourFormat(12, AM)).toBe(0);
});
it("converts 1 AM to 1", () => {
- expect(hourTo24HourFormat(1, 0)).toBe(1);
+ expect(hourTo24HourFormat(1, AM)).toBe(1);
});
it("converts 11 AM to 11", () => {
- expect(hourTo24HourFormat(11, 0)).toBe(11);
+ expect(hourTo24HourFormat(11, AM)).toBe(11);
});
// Test PM cases
it("converts 12 PM to 12", () => {
- expect(hourTo24HourFormat(12, 1)).toBe(12);
+ expect(hourTo24HourFormat(12, PM)).toBe(12);
});
it("converts 1 PM to 13", () => {
- expect(hourTo24HourFormat(1, 1)).toBe(13);
+ expect(hourTo24HourFormat(1, PM)).toBe(13);
});
it("converts 11 PM to 23", () => {
- expect(hourTo24HourFormat(11, 1)).toBe(23);
+ expect(hourTo24HourFormat(11, PM)).toBe(23);
});
// Edge cases
it("converts 0 AM to 0", () => {
- expect(hourTo24HourFormat(0, 0)).toBe(0);
+ expect(hourTo24HourFormat(0, AM)).toBe(0);
});
it("converts 0 PM to 12", () => {
- expect(hourTo24HourFormat(0, 1)).toBe(12);
+ expect(hourTo24HourFormat(0, PM)).toBe(12);
});
it("converts NaN PM to NaN", () => {
- expect(hourTo24HourFormat(NaN, 1)).toBeNaN();
+ expect(hourTo24HourFormat(NaN, PM)).toBeNaN();
});
+});
- it("converts 11 NaN to 11 (that is, fall back to AM if the AM/PM is NaN)", () => {
- expect(hourTo24HourFormat(11, NaN)).toBe(11);
+describe("scheduleValueToCron", () => {
+ it("returns a raw cron expression as is", () => {
+ expect(
+ scheduleValueToCron({ schedule_type: "cron", cron: "0 15 9 ? * 4#1 *" }),
+ ).toBe("0 15 9 ? * 4#1 *");
});
- it("converts NaN NaN to NaN", () => {
- expect(hourTo24HourFormat(NaN, NaN)).toBeNaN();
+ it("leaves a value the user has not picked out of the expression", () => {
+ expect(
+ scheduleValueToCron({
+ schedule_type: "daily",
+ schedule_hour: null,
+ schedule_minute: 0,
+ }),
+ ).toBe("0 0 * * * ? *");
});
});
diff --git a/frontend/src/metabase/common/components/Schedule/strings.ts b/frontend/src/metabase/common/components/Schedule/strings.ts
index 5196632f076..54115174a5d 100644
--- a/frontend/src/metabase/common/components/Schedule/strings.ts
+++ b/frontend/src/metabase/common/components/Schedule/strings.ts
@@ -4,6 +4,9 @@ import _ from "underscore";
import { has24HourModeSetting } from "metabase/utils/time-dayjs";
import type { ScheduleDayType, ScheduleFrameType } from "metabase-types/api";
+import { AM, PM } from "./constants";
+import type { AmPm } from "./types";
+
function intToOption(n: number) {
return {
label: n.toString(),
@@ -124,12 +127,12 @@ export const getScheduleStrings = () => {
| { label: string; value: "calendar-day" }
)[] = [{ label: t`calendar day`, value: "calendar-day" }, ...weekdays];
- const amAndPM = [
+ const amAndPM: { label: string; value: AmPm }[] = [
// We use a fallback string in case the translator translated
// 'AM' or 'PM' as an empty string, which might happen since
// certain cultures do not use AM/PM.
- { label: c("As in 9:00 AM").t`AM`.trim() || "AM", value: "0" },
- { label: c("As in 9:00 PM").t`PM`.trim() || "PM", value: "1" },
+ { label: c("As in 9:00 AM").t`AM`.trim() || "AM", value: AM },
+ { label: c("As in 9:00 PM").t`PM`.trim() || "PM", value: PM },
];
const frames: { label: string; value: ScheduleFrameType }[] = [
diff --git a/frontend/src/metabase/common/components/Schedule/test-utils.tsx b/frontend/src/metabase/common/components/Schedule/test-utils.tsx
index 03328095a50..74caa1a1182 100644
--- a/frontend/src/metabase/common/components/Schedule/test-utils.tsx
+++ b/frontend/src/metabase/common/components/Schedule/test-utils.tsx
@@ -5,11 +5,7 @@ import { mockSettings } from "__support__/settings";
import { createMockEntitiesState } from "__support__/store";
import { renderWithProviders } from "__support__/ui";
import { createMockState } from "metabase/redux/store/mocks";
-import type {
- ScheduleSettings,
- ScheduleType,
- TokenFeatures,
-} from "metabase-types/api";
+import type { TokenFeatures } from "metabase-types/api";
import {
createMockSettings,
createMockTokenFeatures,
@@ -17,12 +13,28 @@ import {
import type { ScheduleProps } from "./Schedule";
import { Schedule } from "./Schedule";
+import type {
+ ScheduleBuilderType,
+ ScheduleChangeEvent,
+ ScheduleValue,
+ ScheduleValueType,
+} from "./types";
+import type { ScheduleDefaults } from "./utils";
+import { getScheduleDefaults } from "./utils";
+
+export const getDefaultsWithoutHour = (
+ scheduleType: ScheduleBuilderType,
+): ScheduleDefaults => ({
+ ...getScheduleDefaults(scheduleType),
+ schedule_hour: null,
+});
+
export interface SetupOpts {
enterprisePlugins?: Parameters<typeof setupEnterpriseOnlyPlugin>[0][];
tokenFeatures?: Partial<TokenFeatures>;
}
-const mockScheduleOptions: ScheduleType[] = [
+const mockScheduleOptions: ScheduleValueType[] = [
"every_n_minutes",
"hourly",
"daily",
@@ -48,65 +60,29 @@ const buildStoreState = ({
export const setup = ({
enterprisePlugins,
tokenFeatures = {},
- ...props
-}: SetupOpts & Partial<ScheduleProps> = {}) => {
- const onScheduleChange = jest.fn();
-
- if (enterprisePlugins) {
- enterprisePlugins.forEach(setupEnterpriseOnlyPlugin);
- }
-
- const propsWithDefaults: ScheduleProps = {
- cronString: props.cronString ?? "0 0 8 * * ? *",
- scheduleOptions: mockScheduleOptions,
- onScheduleChange,
- timezone: mockTimezone,
- verb: mockVerb,
- ...props,
- };
-
- const renderResult = renderWithProviders(
- <Schedule {...propsWithDefaults} />,
- { storeInitialState: buildStoreState({ tokenFeatures }) },
- );
-
- return { ...renderResult, onScheduleChange };
-};
-
-/**
- * Stateful wrapper that holds the cron string in React state and re-renders
- * `<Schedule>` after every change. Required for tests that drive multiple
- * sequential clicks — `<Schedule>` derives its settings from `cronString` on
- * each render, so the parent must update `cronString` for subsequent clicks
- * to see the new state.
- */
-export const setupHarness = ({
- enterprisePlugins,
- tokenFeatures = {},
- initialCronString = "0 0 * * * ? *",
+ value: initialValue,
...props
}: SetupOpts &
- Omit<Partial<ScheduleProps>, "cronString" | "onScheduleChange"> & {
- initialCronString?: string;
- } = {}) => {
- const onScheduleChange = jest.fn<void, [string, ScheduleSettings]>();
+ Omit<Partial<ScheduleProps>, "onScheduleChange"> &
+ Pick<ScheduleProps, "value">) => {
+ const onScheduleChange = jest.fn<void, [ScheduleChangeEvent]>();
if (enterprisePlugins) {
enterprisePlugins.forEach(setupEnterpriseOnlyPlugin);
}
const Harness = () => {
- const [cron, setCron] = useState(initialCronString);
+ const [value, setValue] = useState<ScheduleValue>(initialValue);
return (
<Schedule
- cronString={cron}
scheduleOptions={mockScheduleOptions}
timezone={mockTimezone}
verb={mockVerb}
{...props}
- onScheduleChange={(next, settings) => {
- onScheduleChange(next, settings);
- setCron(next);
+ value={value}
+ onScheduleChange={(event) => {
+ onScheduleChange(event);
+ setValue(event.value);
}}
/>
);
diff --git a/frontend/src/metabase/common/components/Schedule/types.ts b/frontend/src/metabase/common/components/Schedule/types.ts
index 02f1a7e8c35..c2cd75176cd 100644
--- a/frontend/src/metabase/common/components/Schedule/types.ts
+++ b/frontend/src/metabase/common/components/Schedule/types.ts
@@ -1,17 +1,39 @@
import type { ScheduleSettings, ScheduleType } from "metabase-types/api";
+import type { AM, PM } from "./constants";
+
type ScheduleProperty = keyof ScheduleSettings;
export type ScheduleChangeProp = { name: ScheduleProperty; value: unknown };
+export type CronString = string;
+
+export type AmPm = typeof AM | typeof PM;
+
+export type ScheduleValueType = ScheduleType | "every_n_minutes" | "cron";
+export type ScheduleBuilderType = Exclude<ScheduleValueType, "cron">;
+export type ScheduleBuilderValue = Omit<ScheduleSettings, "schedule_type"> & {
+ schedule_type: ScheduleBuilderType;
+};
+
+export type ScheduleCronValue = {
+ schedule_type: "cron";
+ cron: CronString;
+};
+
+export type ScheduleValue = ScheduleBuilderValue | ScheduleCronValue;
+
+export const isScheduleCronValue = (
+ value: ScheduleValue,
+): value is ScheduleCronValue => value.schedule_type === "cron";
+
+export type ScheduleChangeEvent = {
+ value: ScheduleValue;
+ /** Null while a required field is unpicked, rather than a cron with invented
+ * values. */
+ cronString: CronString | null;
+};
+
export type UpdateSchedule = (
field: ScheduleProperty,
value: ScheduleSettings[typeof field],
) => void;
-
-/** A default schedule should assign a value or null to
- * each property of ScheduleSettings
- * */
-export type ScheduleDefaults = Record<
- ScheduleType,
- Required<Omit<ScheduleSettings, "schedule_type">>
->;
diff --git a/frontend/src/metabase/common/components/Schedule/utils.tsx b/frontend/src/metabase/common/components/Schedule/utils.tsx
index c9ae31e2103..796d34637ff 100644
--- a/frontend/src/metabase/common/components/Schedule/utils.tsx
+++ b/frontend/src/metabase/common/components/Schedule/utils.tsx
@@ -5,9 +5,16 @@ import _ from "underscore";
import type { SelectProps } from "metabase/ui";
import type { FontStyle } from "metabase/utils/measure-text";
import { measureTextWidth } from "metabase/utils/measure-text";
+import { isNotNull, removeNullAndUndefinedValues } from "metabase/utils/types";
import type { ScheduleSettings } from "metabase-types/api";
import { defaultDay, defaultHour } from "./constants";
+import type {
+ ScheduleBuilderType,
+ ScheduleBuilderValue,
+ ScheduleValue,
+} from "./types";
+import { isScheduleCronValue } from "./types";
export const combineConsecutiveStrings = (arr: ReactNode[]) => {
return arr.reduce<ReactNode[]>((acc, node) => {
@@ -23,7 +30,7 @@ export const combineConsecutiveStrings = (arr: ReactNode[]) => {
};
export const getLongestSelectLabel = (
- data: SelectProps["data"] | { value: string }[] = [],
+ data: SelectProps<string | null>["data"] | { value: string }[] = [],
fontFamily?: string,
): string => {
const width = (str: string) =>
@@ -67,50 +74,175 @@ export const measureTextWidthSafely = _.memoize(
},
);
-export const getScheduleDefaults = (
- schedule: ScheduleSettings,
-): ScheduleSettings => {
- return match<ScheduleSettings>(schedule)
- .with({ schedule_type: "every_n_minutes" }, () => ({
- schedule_day: null,
- schedule_frame: null,
- schedule_hour: null,
- schedule_minute: 10,
- }))
- .with({ schedule_type: "hourly" }, () => ({
- schedule_day: null,
- schedule_frame: null,
- schedule_hour: null,
- schedule_minute: 0,
- }))
- .with({ schedule_type: "daily" }, () => ({
- schedule_day: null,
- schedule_frame: null,
- schedule_hour: defaultHour,
- schedule_minute: 0,
+const SCHEDULE_FIELDS = [
+ "schedule_day",
+ "schedule_frame",
+ "schedule_hour",
+ "schedule_minute",
+] as const;
+
+export type ScheduleField = (typeof SCHEDULE_FIELDS)[number];
+
+export type ScheduleDefaults = {
+ [Field in ScheduleField]: ScheduleSettings[Field];
+};
+
+type ScheduleFieldSpecs = {
+ defaults: ScheduleDefaults;
+ cron: Partial<Record<ScheduleField, "required" | "wildcard">>;
+};
+
+export type GetScheduleDefaults = (
+ scheduleType: ScheduleBuilderType,
+) => ScheduleDefaults;
+
+const getScheduleFieldSpecs = (
+ scheduleType: ScheduleBuilderType,
+): ScheduleFieldSpecs =>
+ match<ScheduleBuilderType, ScheduleFieldSpecs>(scheduleType)
+ .with("every_n_minutes", () => ({
+ defaults: {
+ schedule_day: null,
+ schedule_frame: null,
+ schedule_hour: null,
+ schedule_minute: 10,
+ },
+ cron: { schedule_minute: "wildcard" },
}))
- .with({ schedule_type: "weekly" }, () => ({
- schedule_day: defaultDay,
- schedule_frame: null,
- schedule_hour: defaultHour,
- schedule_minute: 0,
+ .with("hourly", () => ({
+ defaults: {
+ schedule_day: null,
+ schedule_frame: null,
+ schedule_hour: null,
+ schedule_minute: 0,
+ },
+ cron: { schedule_minute: "wildcard" },
}))
- .with({ schedule_type: "monthly", schedule_frame: "mid" }, () => ({
- schedule_day: null,
- schedule_frame: "mid",
- schedule_hour: defaultHour,
- schedule_minute: 0,
+ .with("daily", () => ({
+ defaults: {
+ schedule_day: null,
+ schedule_frame: null,
+ schedule_hour: defaultHour,
+ schedule_minute: 0,
+ },
+ cron: { schedule_hour: "required", schedule_minute: "wildcard" },
}))
- .with({ schedule_type: "monthly" }, () => ({
- schedule_frame: "first",
- schedule_hour: defaultHour,
- schedule_minute: 0,
+ .with("weekly", () => ({
+ defaults: {
+ schedule_day: defaultDay,
+ schedule_frame: null,
+ schedule_hour: defaultHour,
+ schedule_minute: 0,
+ },
+ cron: {
+ schedule_day: "required",
+ schedule_hour: "required",
+ schedule_minute: "wildcard",
+ },
}))
- .with({ schedule_type: "cron" }, () => ({
- schedule_day: null,
- schedule_frame: null,
- schedule_hour: defaultHour,
- schedule_minute: 0,
+ .with("monthly", () => ({
+ defaults: {
+ schedule_day: null,
+ schedule_frame: "first",
+ schedule_hour: defaultHour,
+ schedule_minute: 0,
+ },
+ cron: {
+ schedule_day: "wildcard",
+ schedule_frame: "required",
+ schedule_hour: "required",
+ schedule_minute: "wildcard",
+ },
}))
- .otherwise(() => ({}));
+ .exhaustive();
+
+export const getScheduleDefaults = (
+ scheduleType: ScheduleBuilderType,
+): ScheduleDefaults => getScheduleFieldSpecs(scheduleType).defaults;
+
+export const getScheduleDefaultsWithoutHour = (
+ scheduleType: ScheduleBuilderType,
+): ScheduleDefaults => ({
+ ...getScheduleDefaults(scheduleType),
+ schedule_hour: null,
+});
+
+const getScheduleFieldsInCron = (
+ scheduleType: ScheduleBuilderType,
+): ScheduleField[] => {
+ const { cron } = getScheduleFieldSpecs(scheduleType);
+ return SCHEDULE_FIELDS.filter((field) => cron[field]);
+};
+
+export const getRequiredScheduleFields = (
+ scheduleType: ScheduleBuilderType,
+): ScheduleField[] => {
+ const { cron } = getScheduleFieldSpecs(scheduleType);
+ return SCHEDULE_FIELDS.filter((field) => cron[field] === "required");
+};
+
+export const clearDayForMidFrame = (
+ schedule: ScheduleBuilderValue,
+): ScheduleBuilderValue =>
+ schedule.schedule_frame === "mid"
+ ? { ...schedule, schedule_day: null }
+ : schedule;
+
+export const resetScheduleToTypeDefaults = (
+ previousValue: ScheduleBuilderValue,
+ nextType: ScheduleBuilderType,
+ getDefaults: GetScheduleDefaults,
+): ScheduleBuilderValue => {
+ const nextValue: ScheduleBuilderValue = {
+ schedule_type: nextType,
+ ...getDefaults(nextType),
+ };
+
+ if (nextType !== "monthly" || previousValue.schedule_frame !== "mid") {
+ return nextValue;
+ }
+
+ return { ...nextValue, schedule_frame: "mid" };
+};
+
+export const clearUnusedScheduleFields = (
+ schedule: ScheduleBuilderValue,
+): ScheduleBuilderValue => {
+ const fieldsInCron = getScheduleFieldsInCron(schedule.schedule_type);
+ const nextValue = SCHEDULE_FIELDS.reduce<ScheduleBuilderValue>(
+ (memo, field) =>
+ fieldsInCron.includes(field) ? memo : { ...memo, [field]: null },
+ schedule,
+ );
+
+ return clearDayForMidFrame(nextValue);
+};
+
+export const toScheduleSettings = (value: ScheduleValue): ScheduleSettings => {
+ if (isScheduleCronValue(value) || value.schedule_type === "every_n_minutes") {
+ throw new Error(
+ `A ${value.schedule_type} schedule cannot be stored as a schedule map`,
+ );
+ }
+ return { ...value, schedule_type: value.schedule_type };
+};
+
+export const isScheduleComplete = (value: ScheduleValue): boolean =>
+ isScheduleCronValue(value) ||
+ getRequiredScheduleFields(value.schedule_type).every((field) =>
+ isNotNull(value[field]),
+ );
+
+export const normalizeScheduleValue = (
+ value: ScheduleValue,
+ getDefaults: GetScheduleDefaults,
+): ScheduleValue => {
+ if (isScheduleCronValue(value)) {
+ return value;
+ }
+
+ return _.defaults(
+ removeNullAndUndefinedValues(value),
+ getDefaults(value.schedule_type),
+ );
};
diff --git a/frontend/src/metabase/common/components/Schedule/utils.unit.spec.tsx b/frontend/src/metabase/common/components/Schedule/utils.unit.spec.tsx
index 283e29a7068..50fae9228ff 100644
--- a/frontend/src/metabase/common/components/Schedule/utils.unit.spec.tsx
+++ b/frontend/src/metabase/common/components/Schedule/utils.unit.spec.tsx
@@ -1,6 +1,15 @@
import type { SelectProps } from "metabase/ui";
-import { combineConsecutiveStrings, getLongestSelectLabel } from "./utils";
+import { getDefaultsWithoutHour } from "./test-utils";
+import type { ScheduleBuilderValue, ScheduleValue } from "./types";
+import {
+ combineConsecutiveStrings,
+ getLongestSelectLabel,
+ getScheduleDefaults,
+ isScheduleComplete,
+ normalizeScheduleValue,
+ resetScheduleToTypeDefaults,
+} from "./utils";
describe("Schedule utility functions", () => {
describe("getLongestSelectLabel", () => {
@@ -84,3 +93,163 @@ describe("combineConsecutiveStrings", () => {
expect(combineConsecutiveStrings(input)).toEqual(expectedOutput);
});
});
+
+describe("isScheduleComplete", () => {
+ it.each(["daily", "weekly", "monthly"] as const)(
+ "should be false when a %s schedule has no hour",
+ (schedule_type) => {
+ expect(isScheduleComplete({ schedule_type, schedule_hour: null })).toBe(
+ false,
+ );
+ },
+ );
+
+ it.each<ScheduleBuilderValue>([
+ { schedule_type: "daily", schedule_hour: 8 },
+ { schedule_type: "weekly", schedule_hour: 8, schedule_day: "mon" },
+ { schedule_type: "monthly", schedule_hour: 8, schedule_frame: "first" },
+ ])("should be true for a complete $schedule_type schedule", (schedule) => {
+ expect(isScheduleComplete(schedule)).toBe(true);
+ });
+
+ it("should be false when a weekly schedule has no day", () => {
+ expect(
+ isScheduleComplete({
+ schedule_type: "weekly",
+ schedule_hour: 8,
+ schedule_day: null,
+ }),
+ ).toBe(false);
+ });
+
+ it("should be false when a monthly schedule has no frame", () => {
+ expect(
+ isScheduleComplete({
+ schedule_type: "monthly",
+ schedule_hour: 8,
+ schedule_frame: null,
+ }),
+ ).toBe(false);
+ });
+
+ it("should treat midnight as a picked hour", () => {
+ expect(
+ isScheduleComplete({ schedule_type: "daily", schedule_hour: 0 }),
+ ).toBe(true);
+ });
+
+ it.each(["every_n_minutes", "hourly"] as const)(
+ "should be true for a %s schedule, which needs no hour",
+ (schedule_type) => {
+ expect(isScheduleComplete({ schedule_type })).toBe(true);
+ },
+ );
+
+ it("should be true for a raw cron expression", () => {
+ expect(
+ isScheduleComplete({ schedule_type: "cron", cron: "0 0 8 * * ? *" }),
+ ).toBe(true);
+ });
+});
+
+describe("normalizeScheduleValue", () => {
+ it("should fill in values the user has not picked", () => {
+ expect(
+ normalizeScheduleValue(
+ { schedule_type: "daily", schedule_hour: null },
+ getScheduleDefaults,
+ ),
+ ).toEqual({
+ schedule_type: "daily",
+ schedule_day: null,
+ schedule_frame: null,
+ schedule_hour: 8,
+ schedule_minute: 0,
+ });
+ });
+
+ it("should keep picked values", () => {
+ expect(
+ normalizeScheduleValue(
+ {
+ schedule_type: "weekly",
+ schedule_day: "fri",
+ schedule_hour: 20,
+ schedule_minute: 15,
+ },
+ getScheduleDefaults,
+ ),
+ ).toEqual({
+ schedule_type: "weekly",
+ schedule_day: "fri",
+ schedule_frame: null,
+ schedule_hour: 20,
+ schedule_minute: 15,
+ });
+ });
+
+ it("should leave a raw cron expression untouched", () => {
+ const value: ScheduleValue = {
+ schedule_type: "cron",
+ cron: "0 0 8 * * ? *",
+ };
+ expect(normalizeScheduleValue(value, getScheduleDefaults)).toEqual(value);
+ });
+});
+
+describe("resetScheduleToTypeDefaults", () => {
+ const daily: ScheduleBuilderValue = {
+ schedule_type: "daily",
+ schedule_day: null,
+ schedule_frame: null,
+ schedule_hour: 20,
+ schedule_minute: 0,
+ };
+
+ it("should apply the defaults of the new type", () => {
+ expect(
+ resetScheduleToTypeDefaults(
+ { schedule_type: "hourly" },
+ "weekly",
+ getScheduleDefaults,
+ ),
+ ).toEqual({
+ schedule_type: "weekly",
+ schedule_day: "mon",
+ schedule_frame: null,
+ schedule_hour: 8,
+ schedule_minute: 0,
+ });
+ });
+
+ it("should keep the monthly frame the previous schedule was on", () => {
+ expect(
+ resetScheduleToTypeDefaults(
+ { ...daily, schedule_frame: "mid" },
+ "monthly",
+ getScheduleDefaults,
+ ),
+ ).toEqual({
+ schedule_type: "monthly",
+ schedule_day: null,
+ schedule_frame: "mid",
+ schedule_hour: 8,
+ schedule_minute: 0,
+ });
+ });
+
+ it("should give no hour to a type that does not need one", () => {
+ expect(
+ resetScheduleToTypeDefaults(daily, "hourly", getScheduleDefaults),
+ ).toMatchObject({
+ schedule_type: "hourly",
+ schedule_hour: null,
+ });
+ });
+
+ it("should leave the hour unpicked when the defaults do not supply one", () => {
+ expect(
+ resetScheduleToTypeDefaults(daily, "weekly", getDefaultsWithoutHour),
+ ).toMatchObject({ schedule_type: "weekly", schedule_hour: null });
+ });
+});
diff --git a/frontend/src/metabase/common/components/SendTestPulse/SendTestPulse.tsx b/frontend/src/metabase/common/components/SendTestPulse/SendTestPulse.tsx
index 236affa8de1..5769a3090c3 100644
--- a/frontend/src/metabase/common/components/SendTestPulse/SendTestPulse.tsx
+++ b/frontend/src/metabase/common/components/SendTestPulse/SendTestPulse.tsx
@@ -27,7 +27,7 @@ export function SendTestPulse<T extends DashboardSubscriptionData>({
}: SendTestPulseProps<T>): JSX.Element {
const onTestPulseChannel = useCallback(() => {
const channelPulse = { ...pulse, channels: [channel] };
- const cleanedPulse = cleanPulse(channelPulse, channelSpecs);
+ const cleanedPulse = cleanPulse(channelPulse, channelSpecs, false);
return testPulse(cleanedPulse);
}, [pulse, channel, channelSpecs, testPulse]);
diff --git a/frontend/src/metabase/dashboard/components/DashboardSubscriptionsSidebar/AddEditSidebar/AddEditEmailSidebar.tsx b/frontend/src/metabase/dashboard/components/DashboardSubscriptionsSidebar/AddEditSidebar/AddEditEmailSidebar.tsx
index e0cd23561bf..b1a3160432c 100644
--- a/frontend/src/metabase/dashboard/components/DashboardSubscriptionsSidebar/AddEditSidebar/AddEditEmailSidebar.tsx
+++ b/frontend/src/metabase/dashboard/components/DashboardSubscriptionsSidebar/AddEditSidebar/AddEditEmailSidebar.tsx
@@ -3,15 +3,22 @@ import { useEffect } from "react";
import { t } from "ttag";
import _ from "underscore";
-import { Schedule, toCronString } from "metabase/common/components/Schedule";
-import type { ScheduleChangeProp } from "metabase/common/components/Schedule/types";
+import { Schedule } from "metabase/common/components/Schedule";
+import type {
+ ScheduleChangeProp,
+ ScheduleValue,
+} from "metabase/common/components/Schedule/types";
+import {
+ getScheduleDefaultsWithoutHour,
+ toScheduleSettings,
+} from "metabase/common/components/Schedule/utils";
import { SendTestPulse } from "metabase/common/components/SendTestPulse";
import { Sidebar } from "metabase/common/components/Sidebar";
import CS from "metabase/css/core/index.css";
import { isEmbeddingSdk } from "metabase/embedding-sdk/config";
import { RecipientPicker } from "metabase/notifications/channels/RecipientPicker";
import { PLUGIN_DASHBOARD_SUBSCRIPTION_PARAMETERS_SECTION_OVERRIDE } from "metabase/plugins";
-import { dashboardPulseIsValid } from "metabase/pulse";
+import { channelTargetIsValid, dashboardPulseIsValid } from "metabase/pulse";
import { useSelector } from "metabase/redux";
import type { DraftDashboardSubscription } from "metabase/redux/store";
import { canAccessSettings, getUser } from "metabase/selectors/user";
@@ -81,6 +88,7 @@ export const AddEditEmailSidebar = ({
setPulseParameters,
}: AddEditEmailSidebarProps) => {
const isValid = dashboardPulseIsValid(pulse, formInput.channels);
+ const hasValidTarget = channelTargetIsValid(channel, channelSpec);
const userCanAccessSettings = useSelector(canAccessSettings);
const currentUser = useSelector(getUser);
const applicationName = useSelector(getApplicationName);
@@ -88,9 +96,9 @@ export const AddEditEmailSidebar = ({
getSetting(state, "report-timezone-short"),
);
- const renderScheduleDescription = (schedule: ScheduleSettings) => {
+ const renderScheduleDescription = (value: ScheduleValue) => {
const description = getSubscriptionScheduleDescription({
- schedule,
+ schedule: toScheduleSettings(value),
channelSpec,
applicationName,
timezone,
@@ -143,22 +151,21 @@ export const AddEditEmailSidebar = ({
)}
<Schedule
mt="md"
- cronString={toCronString(
- _.pick(
- channel,
- "schedule_day",
- "schedule_frame",
- "schedule_hour",
- "schedule_type",
- ),
+ value={_.pick(
+ channel,
+ "schedule_day",
+ "schedule_frame",
+ "schedule_hour",
+ "schedule_type",
)}
scheduleOptions={channelSpec.schedules}
verb={t`Sent`}
+ getDefaults={getScheduleDefaultsWithoutHour}
renderScheduleDescription={renderScheduleDescription}
- onScheduleChange={(_cronString, newSchedule) =>
- onChannelScheduleChange(newSchedule, {
+ onScheduleChange={({ value }) =>
+ onChannelScheduleChange(toScheduleSettings(value), {
name: "schedule_type",
- value: newSchedule.schedule_type,
+ value: value.schedule_type,
})
}
/>
@@ -170,7 +177,7 @@ export const AddEditEmailSidebar = ({
testPulse={testPulse}
normalText={t`Send email now`}
successText={t`Email sent`}
- disabled={!isValid}
+ disabled={!hasValidTarget}
/>
</div>
{PLUGIN_DASHBOARD_SUBSCRIPTION_PARAMETERS_SECTION_OVERRIDE.Component ? (
diff --git a/frontend/src/metabase/dashboard/components/DashboardSubscriptionsSidebar/AddEditSidebar/AddEditSlackSidebar.tsx b/frontend/src/metabase/dashboard/components/DashboardSubscriptionsSidebar/AddEditSidebar/AddEditSlackSidebar.tsx
index fa0ae2f2cb2..bfdcc541843 100644
--- a/frontend/src/metabase/dashboard/components/DashboardSubscriptionsSidebar/AddEditSidebar/AddEditSlackSidebar.tsx
+++ b/frontend/src/metabase/dashboard/components/DashboardSubscriptionsSidebar/AddEditSidebar/AddEditSlackSidebar.tsx
@@ -3,14 +3,20 @@ import { t } from "ttag";
import _ from "underscore";
import { Schedule } from "metabase/common/components/Schedule/Schedule";
-import { toCronString } from "metabase/common/components/Schedule/cron";
-import type { ScheduleChangeProp } from "metabase/common/components/Schedule/types";
+import type {
+ ScheduleChangeProp,
+ ScheduleValue,
+} from "metabase/common/components/Schedule/types";
+import {
+ getScheduleDefaultsWithoutHour,
+ toScheduleSettings,
+} from "metabase/common/components/Schedule/utils";
import { SendTestPulse } from "metabase/common/components/SendTestPulse";
import { Sidebar } from "metabase/common/components/Sidebar";
import CS from "metabase/css/core/index.css";
import { SlackChannelField } from "metabase/notifications/channels/SlackChannelField";
import { PLUGIN_DASHBOARD_SUBSCRIPTION_PARAMETERS_SECTION_OVERRIDE } from "metabase/plugins";
-import { dashboardPulseIsValid } from "metabase/pulse";
+import { channelTargetIsValid, dashboardPulseIsValid } from "metabase/pulse";
import { useSelector } from "metabase/redux";
import type { DraftDashboardSubscription } from "metabase/redux/store";
import { getApplicationName } from "metabase/selectors/whitelabel";
@@ -72,14 +78,15 @@ export const AddEditSlackSidebar = ({
setPulseParameters,
}: AddEditSlackSidebarProps) => {
const isValid = dashboardPulseIsValid(pulse, formInput.channels);
+ const hasValidTarget = channelTargetIsValid(channel, channelSpec);
const applicationName = useSelector(getApplicationName);
const timezone = useSelector((state) =>
getSetting(state, "report-timezone-short"),
);
- const renderScheduleDescription = (schedule: ScheduleSettings) => {
+ const renderScheduleDescription = (value: ScheduleValue) => {
const description = getSubscriptionScheduleDescription({
- schedule,
+ schedule: toScheduleSettings(value),
channelSpec,
applicationName,
timezone,
@@ -125,22 +132,21 @@ export const AddEditSlackSidebar = ({
)}
<Schedule
mt="md"
- cronString={toCronString(
- _.pick(
- channel,
- "schedule_day",
- "schedule_frame",
- "schedule_hour",
- "schedule_type",
- ),
+ value={_.pick(
+ channel,
+ "schedule_day",
+ "schedule_frame",
+ "schedule_hour",
+ "schedule_type",
)}
scheduleOptions={channelSpec.schedules}
verb={t`Send`}
+ getDefaults={getScheduleDefaultsWithoutHour}
renderScheduleDescription={renderScheduleDescription}
- onScheduleChange={(_cronString, newSchedule) =>
- onChannelScheduleChange(newSchedule, {
+ onScheduleChange={({ value }) =>
+ onChannelScheduleChange(toScheduleSettings(value), {
name: "schedule_type",
- value: newSchedule.schedule_type,
+ value: value.schedule_type,
})
}
/>
@@ -152,7 +158,7 @@ export const AddEditSlackSidebar = ({
testPulse={testPulse}
normalText={t`Send to Slack now`}
successText={t`Slack sent`}
- disabled={!isValid}
+ disabled={!hasValidTarget}
/>
</div>
diff --git a/frontend/src/metabase/dashboard/components/DashboardSubscriptionsSidebar/tests/common.unit.spec.ts b/frontend/src/metabase/dashboard/components/DashboardSubscriptionsSidebar/tests/common.unit.spec.ts
index 5f474f0a0ae..f95be603927 100644
--- a/frontend/src/metabase/dashboard/components/DashboardSubscriptionsSidebar/tests/common.unit.spec.ts
+++ b/frontend/src/metabase/dashboard/components/DashboardSubscriptionsSidebar/tests/common.unit.spec.ts
@@ -4,7 +4,13 @@ import fetchMock from "fetch-mock";
import { screen, within } from "__support__/ui";
import type { DashboardSubscription } from "metabase-types/api";
-import { dashcard, hasBasicFilterOptions, setup, user } from "./setup";
+import {
+ dashcard,
+ hasBasicFilterOptions,
+ selectScheduleTime,
+ setup,
+ user,
+} from "./setup";
describe("DashboardSubscriptionsSidebar", () => {
it("should forward non-admin to email form - when slack is not setup", async () => {
@@ -264,6 +270,8 @@ describe("DashboardSubscriptionsSidebar", () => {
within(await screen.findByRole("listbox")).getByText("daily"),
);
+ await selectScheduleTime();
+
expect(
await screen.findByText(
"Slack messages will be sent at 8:00 AM UTC, your Metabase timezone.",
@@ -317,6 +325,8 @@ describe("DashboardSubscriptionsSidebar", () => {
within(await screen.findByRole("listbox")).getByText("daily"),
);
+ await selectScheduleTime();
+
expect(
await screen.findByText(
"Emails will be sent at 8:00 AM UTC, your Metabase timezone.",
@@ -346,6 +356,37 @@ describe("DashboardSubscriptionsSidebar", () => {
expect(payload.cards[0].id).toEqual(dashcard.id);
});
+ it("should keep 'Send email now' enabled when the frequency change clears the time", async () => {
+ setup();
+
+ await userEvent.click(await screen.findByText("Email it"));
+ await userEvent.click(
+ await screen.findByPlaceholderText(
+ "Enter user names or email addresses",
+ ),
+ );
+ await userEvent.click(
+ await screen.findByText(`${user.first_name} ${user.last_name}`),
+ );
+
+ await userEvent.click(screen.getByTestId("select-frequency"));
+ await userEvent.click(
+ within(await screen.findByRole("listbox")).getByText("weekly"),
+ );
+
+ const sendNowButton = screen.getByRole("button", {
+ name: "Send email now",
+ });
+ expect(screen.getByRole("button", { name: "Done" })).toBeDisabled();
+ expect(sendNowButton).toBeEnabled();
+
+ await userEvent.click(sendNowButton);
+
+ const lastCall = fetchMock.callHistory.lastCall("path:/api/pulse/test");
+ const payload = await lastCall?.request?.json();
+ expect(payload.channels).toHaveLength(1);
+ });
+
it("should persist the include_pdf channel detail when the PDF switch is toggled on", async () => {
setup();
diff --git a/frontend/src/metabase/dashboard/components/DashboardSubscriptionsSidebar/tests/setup.tsx b/frontend/src/metabase/dashboard/components/DashboardSubscriptionsSidebar/tests/setup.tsx
index e87a3fa5d42..6b6cefec387 100644
--- a/frontend/src/metabase/dashboard/components/DashboardSubscriptionsSidebar/tests/setup.tsx
+++ b/frontend/src/metabase/dashboard/components/DashboardSubscriptionsSidebar/tests/setup.tsx
@@ -1,4 +1,5 @@
/* istanbul ignore file */
+import userEvent from "@testing-library/user-event";
import fetchMock from "fetch-mock";
import { setupEnterpriseOnlyPlugin } from "__support__/enterprise";
@@ -6,7 +7,7 @@ import { setupUserRecipientsEndpoint } from "__support__/server-mocks";
import { setupNotificationChannelsEndpoints } from "__support__/server-mocks/pulse";
import { mockSettings } from "__support__/settings";
import type { Screen } from "__support__/ui";
-import { renderWithProviders } from "__support__/ui";
+import { renderWithProviders, screen } from "__support__/ui";
import { getNextId } from "__support__/utils";
import { MockDashboardContext } from "metabase/dashboard/context/mock-context";
import { isEmbeddingSdk as mockIsEmbeddingSdk } from "metabase/embedding-sdk/config";
@@ -243,6 +244,11 @@ export const hasAdvancedFilterOptionsHidden = (screen: Screen) => {
return true;
};
+export const selectScheduleTime = async (time = "8:00") => {
+ await userEvent.click(screen.getByTestId("select-time"));
+ await userEvent.click(screen.getByRole("option", { name: time }));
+};
+
export const hasBasicFilterOptions = (screen: Screen) => {
expect(
screen.getByText(
diff --git a/frontend/src/metabase/databases/components/DatabaseCacheScheduleField/DatabaseCacheScheduleField.tsx b/frontend/src/metabase/databases/components/DatabaseCacheScheduleField/DatabaseCacheScheduleField.tsx
index 8d0c1aea0f0..cf3dbd11463 100644
--- a/frontend/src/metabase/databases/components/DatabaseCacheScheduleField/DatabaseCacheScheduleField.tsx
+++ b/frontend/src/metabase/databases/components/DatabaseCacheScheduleField/DatabaseCacheScheduleField.tsx
@@ -4,7 +4,8 @@ import { useCallback } from "react";
import { match } from "ts-pattern";
import { t } from "ttag";
-import { Schedule, toCronString } from "metabase/common/components/Schedule";
+import { Schedule } from "metabase/common/components/Schedule";
+import type { ScheduleChangeEvent } from "metabase/common/components/Schedule/types";
import { FormField } from "metabase/forms";
import { Box, rem } from "metabase/ui";
import type {
@@ -40,9 +41,7 @@ export const DatabaseCacheScheduleField = ({
const [{ value }, , { setValue }] = useField(name);
const handleScheduleChange = useCallback(
- (value: ScheduleSettings) => {
- setValue(value);
- },
+ ({ value }: ScheduleChangeEvent) => setValue(value),
[setValue],
);
@@ -92,11 +91,9 @@ export const DatabaseCacheScheduleField = ({
{scheduleMode === "full" && (
<Schedule
mt="md"
- cronString={toCronString(value ?? DEFAULT_SCHEDULE)}
+ value={value ?? DEFAULT_SCHEDULE}
scheduleOptions={SCHEDULE_OPTIONS}
- onScheduleChange={(_cronString, nextSchedule) =>
- handleScheduleChange(nextSchedule)
- }
+ onScheduleChange={handleScheduleChange}
/>
)}
diff --git a/frontend/src/metabase/databases/components/DatabaseSyncScheduleField/DatabaseSyncScheduleField.tsx b/frontend/src/metabase/databases/components/DatabaseSyncScheduleField/DatabaseSyncScheduleField.tsx
index e8a44dbcea9..a4e9086031c 100644
--- a/frontend/src/metabase/databases/components/DatabaseSyncScheduleField/DatabaseSyncScheduleField.tsx
+++ b/frontend/src/metabase/databases/components/DatabaseSyncScheduleField/DatabaseSyncScheduleField.tsx
@@ -3,7 +3,8 @@ import type { ReactNode } from "react";
import { useCallback } from "react";
import { t } from "ttag";
-import { Schedule, toCronString } from "metabase/common/components/Schedule";
+import { Schedule } from "metabase/common/components/Schedule";
+import type { ScheduleChangeEvent } from "metabase/common/components/Schedule/types";
import { FormField } from "metabase/forms";
import type { ScheduleSettings, ScheduleType } from "metabase-types/api";
@@ -30,9 +31,7 @@ const DatabaseSyncScheduleField = ({
const [{ value }, , { setValue }] = useField(name);
const handleScheduleChange = useCallback(
- (value: ScheduleSettings) => {
- setValue(value);
- },
+ ({ value }: ScheduleChangeEvent) => setValue(value),
[setValue],
);
@@ -40,13 +39,11 @@ const DatabaseSyncScheduleField = ({
<FormField title={title} description={description}>
<Schedule
mt="md"
- cronString={toCronString(value ?? DEFAULT_SCHEDULE)}
+ value={value ?? DEFAULT_SCHEDULE}
scheduleOptions={SCHEDULE_OPTIONS}
verb={t`Sync`}
minutesOnHourPicker
- onScheduleChange={(_cronString, nextSchedule) =>
- handleScheduleChange(nextSchedule)
- }
+ onScheduleChange={handleScheduleChange}
/>
</FormField>
);
diff --git a/frontend/src/metabase/notifications/channels/SlackChannelField.unit.spec.tsx b/frontend/src/metabase/notifications/channels/SlackChannelField.unit.spec.tsx
index 14a27a01ba2..60e25824158 100644
--- a/frontend/src/metabase/notifications/channels/SlackChannelField.unit.spec.tsx
+++ b/frontend/src/metabase/notifications/channels/SlackChannelField.unit.spec.tsx
@@ -71,7 +71,11 @@ function setup({ channel }: { channel: Channel }) {
describe("SlackChannelField channel_id storage", () => {
it("stores channel_id when user selects a known channel", async () => {
const { spy } = setup({
- channel: { channel_type: "slack", details: { channel: "" } },
+ channel: {
+ channel_type: "slack",
+ schedule_type: "hourly",
+ details: { channel: "" },
+ },
});
const input = screen.getByPlaceholderText("Pick a user or channel...");
@@ -88,6 +92,7 @@ describe("SlackChannelField channel_id storage", () => {
const { spy } = setup({
channel: {
channel_type: "slack",
+ schedule_type: "hourly",
details: { channel: "#general", channel_id: "C001" },
},
});
@@ -107,6 +112,7 @@ describe("SlackChannelField channel_id storage", () => {
const { spy } = setup({
channel: {
channel_type: "slack",
+ schedule_type: "hourly",
details: { channel: "#general", channel_id: "C001" },
},
});
diff --git a/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/CreateOrEditQuestionAlertModal.tsx b/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/CreateOrEditQuestionAlertModal.tsx
index 159e7f63024..f8aea042693 100644
--- a/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/CreateOrEditQuestionAlertModal.tsx
+++ b/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/CreateOrEditQuestionAlertModal.tsx
@@ -10,6 +10,7 @@ import {
useSendUnsavedNotificationMutation,
useUpdateNotificationMutation,
} from "metabase/api";
+import type { ScheduleValueType } from "metabase/common/components/Schedule/types";
import CS from "metabase/css/core/index.css";
import { isEmbeddingSdk } from "metabase/embedding-sdk/config";
import {
@@ -48,7 +49,6 @@ import type {
NotificationCardSendCondition,
NotificationCronSubscription,
NotificationHandler,
- ScheduleType,
UpdateAlertNotificationRequest,
UserId,
VisualizationSettings,
@@ -85,7 +85,7 @@ function getAlertTriggerOptionsMap(
};
}
-const ALERT_SCHEDULE_OPTIONS: ScheduleType[] = [
+const ALERT_SCHEDULE_OPTIONS: ScheduleValueType[] = [
"every_n_minutes",
"hourly",
"daily",
@@ -136,7 +136,6 @@ export const CreateOrEditQuestionAlertModal = ({
const questionId = question.id();
const isEditMode = !!editingNotification;
- const subscription = notification?.subscriptions[0];
const { data: channelSpec, isLoading: isLoadingChannelInfo } =
useGetChannelInfoQuery();
@@ -261,17 +260,24 @@ export const CreateOrEditQuestionAlertModal = ({
: hasConfiguredEmailOrSlackChannel; // webhooks are available only for users with "Settings access" permission - WRK-63
const handleScheduleChange = useCallback(
- (updatedSubscription: NotificationCronSubscription) => {
- if (!subscription) {
+ (updatedSubscription?: NotificationCronSubscription) => {
+ if (!notification) {
return;
}
setNotification({
...notification,
- subscriptions: [updatedSubscription],
+ subscriptions: updatedSubscription
+ ? [
+ {
+ ...editingNotification?.subscriptions[0],
+ ...updatedSubscription,
+ },
+ ]
+ : [],
});
},
- [setNotification, subscription, notification],
+ [setNotification, notification, editingNotification],
);
if (!isLoadingChannelInfo && channelSpec && !channelRequirementsMet) {
@@ -283,7 +289,7 @@ export const CreateOrEditQuestionAlertModal = ({
);
}
- if (!notification || !subscription) {
+ if (!notification) {
return null;
}
@@ -361,7 +367,7 @@ export const CreateOrEditQuestionAlertModal = ({
}}
>
<NotificationSchedule
- subscription={subscription}
+ initialSubscription={notification?.subscriptions[0]}
scheduleOptions={ALERT_SCHEDULE_OPTIONS}
onScheduleChange={handleScheduleChange}
/>
diff --git a/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/CreateOrEditQuestionAlertModal.unit.spec.tsx b/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/CreateOrEditQuestionAlertModal.unit.spec.tsx
index aeee62e421b..84b601f9fb2 100644
--- a/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/CreateOrEditQuestionAlertModal.unit.spec.tsx
+++ b/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/CreateOrEditQuestionAlertModal.unit.spec.tsx
@@ -141,7 +141,7 @@ describe("CreateOrEditQuestionAlertModal", () => {
).toBeInTheDocument();
});
- it("should show daily and 8am as default schedule settings", async () => {
+ it("should show daily schedule with no time selected by default", async () => {
setup({
isAdmin: true,
isEmailSetup: true,
@@ -151,13 +151,20 @@ describe("CreateOrEditQuestionAlertModal", () => {
expect(screen.getByText("New alert")).toBeInTheDocument();
});
- // Find the schedule type select (showing "daily")
const scheduleTypeSelect = screen.getByTestId("select-frequency");
expect(scheduleTypeSelect).toHaveValue("daily");
- // Find the time selector (showing "8:00")
const timeSelector = screen.getByTestId("select-time");
- expect(timeSelector).toHaveValue("8:00");
+ expect(timeSelector).toHaveValue("");
+ expect(timeSelector).toHaveAttribute("placeholder", "HH:MM");
+ expect(
+ within(screen.getByTestId("select-am-pm")).getByRole("radio", {
+ name: "AM",
+ }),
+ ).toBeChecked();
+
+ expect(screen.getByRole("button", { name: /done/i })).toBeDisabled();
+ expect(screen.getByRole("button", { name: /send now/i })).toBeEnabled();
});
it("should show the editing alert data when in edit mode", async () => {
@@ -269,13 +276,16 @@ describe("CreateOrEditQuestionAlertModal", () => {
const scheduleTypeSelect = screen.getByTestId("select-frequency");
expect(scheduleTypeSelect).toHaveValue("daily");
- // Change time from default 9:00 to 8:00
+ expect(screen.getByRole("button", { name: /done/i })).toBeDisabled();
+
+ // Explicitly select 8:00 as the alert time
const timeSelector = screen.getByTestId("select-time");
await userEvent.click(timeSelector);
const option8am = screen.getByRole("option", { name: /8:00/i });
await userEvent.click(option8am);
const saveButton = screen.getByRole("button", { name: /done/i });
+ expect(saveButton).toBeEnabled();
await userEvent.click(saveButton);
// Verify the API was called with the correct cron schedule for 8am
@@ -284,8 +294,7 @@ describe("CreateOrEditQuestionAlertModal", () => {
await waitFor(async () => {
const requestBody = await calls[0].options?.body;
- // Unjustified type cast. FIXME
- const subscription = JSON.parse(requestBody as string).subscriptions[0];
+ const subscription = JSON.parse(String(requestBody)).subscriptions[0];
// Verify the cron schedule is for 8am daily
expect(subscription.cron_schedule).toBe("0 0 8 * * ? *");
@@ -294,6 +303,40 @@ describe("CreateOrEditQuestionAlertModal", () => {
expect(onAlertCreatedMock).toHaveBeenCalledTimes(1);
});
+ it("should create a new notification with hourly schedule", async () => {
+ fetchMock.postOnce("path:/api/notification", { body: { id: 123 } });
+ const onAlertCreatedMock = jest.fn();
+
+ setup({
+ isAdmin: true,
+ isEmailSetup: true,
+ onAlertCreatedMock,
+ });
+
+ await waitFor(() => {
+ expect(screen.getByText("New alert")).toBeInTheDocument();
+ });
+
+ await userEvent.click(screen.getByTestId("select-frequency"));
+ await userEvent.click(screen.getByRole("option", { name: /hourly/i }));
+
+ const saveButton = screen.getByRole("button", { name: /done/i });
+ expect(saveButton).toBeEnabled();
+ await userEvent.click(saveButton);
+
+ const calls = fetchMock.callHistory.calls("path:/api/notification");
+ expect(calls.length).toBe(1);
+
+ await waitFor(async () => {
+ const requestBody = await calls[0].options?.body;
+ const subscription = JSON.parse(String(requestBody)).subscriptions[0];
+
+ expect(subscription.cron_schedule).toBe("0 0 * * * ? *");
+ });
+
+ expect(onAlertCreatedMock).toHaveBeenCalledTimes(1);
+ });
+
it("should create a new notification with custom schedule", async () => {
// Setup fetchMock for API call - note we use '*' matcher to capture any request to this endpoint
fetchMock.postOnce("path:/api/notification", { body: { id: 123 } });
@@ -316,7 +359,8 @@ describe("CreateOrEditQuestionAlertModal", () => {
const optionCustom = screen.getByRole("option", { name: /custom/i });
await userEvent.click(optionCustom);
- const cronInput = screen.getByDisplayValue("0 8 * * ?");
+ // A new alert has no hour picked yet, so the hour is left as a wildcard
+ const cronInput = screen.getByDisplayValue("0 * * * ?");
await userEvent.clear(cronInput);
await userEvent.type(cronInput, "0/10 8 * * ?");
@@ -330,8 +374,7 @@ describe("CreateOrEditQuestionAlertModal", () => {
await waitFor(async () => {
const requestBody = await calls[0].options?.body;
- // Unjustified type cast. FIXME
- const subscription = JSON.parse(requestBody as string).subscriptions[0];
+ const subscription = JSON.parse(String(requestBody)).subscriptions[0];
// Verify the cron schedule is for 8am daily
expect(subscription.cron_schedule).toBe("0 0/10 8 * * ? *");
@@ -445,8 +488,7 @@ describe("CreateOrEditQuestionAlertModal", () => {
await waitFor(async () => {
const requestBody = await calls[0].options?.body;
- // Unjustified type cast. FIXME
- const subscription = JSON.parse(requestBody as string).subscriptions[0];
+ const subscription = JSON.parse(String(requestBody)).subscriptions[0];
// Verify the cron schedule is for Tuesday at 2pm (day 3)
expect(subscription.cron_schedule).toBe("0 0 14 ? * 3 *");
@@ -455,6 +497,67 @@ describe("CreateOrEditQuestionAlertModal", () => {
expect(onAlertUpdatedMock).toHaveBeenCalledTimes(1);
});
+ it("should keep the subscription identity when the schedule loses its time and gets a new one", async () => {
+ const notificationId = 42;
+ const subscriptionId = 7;
+ fetchMock.putOnce(`path:/api/notification/${notificationId}`, {
+ body: { id: notificationId },
+ });
+
+ const mockNotification = createMockNotification({
+ id: notificationId,
+ subscriptions: [
+ createMockNotificationCronSubscription({
+ id: subscriptionId,
+ notification_id: notificationId,
+ cron_schedule: "0 0 9 * * ?",
+ }),
+ ],
+ });
+
+ setup({
+ isAdmin: true,
+ isEmailSetup: true,
+ editingNotification: mockNotification,
+ });
+
+ await waitFor(() => {
+ expect(screen.getByText("Edit alert")).toBeInTheDocument();
+ });
+
+ // Going through Custom drops the hour, so the alert is left without a
+ // subscription until a new time is picked
+ await userEvent.click(screen.getByTestId("select-frequency"));
+ await userEvent.click(screen.getByRole("option", { name: /custom/i }));
+
+ await userEvent.click(screen.getByTestId("select-frequency"));
+ await userEvent.click(screen.getByRole("option", { name: /daily/i }));
+
+ expect(
+ screen.getByRole("button", { name: /save changes/i }),
+ ).toBeDisabled();
+
+ await userEvent.click(screen.getByTestId("select-time"));
+ await userEvent.click(screen.getByRole("option", { name: /10:00/i }));
+
+ const saveButton = screen.getByRole("button", { name: /save changes/i });
+ expect(saveButton).toBeEnabled();
+ await userEvent.click(saveButton);
+
+ const calls = fetchMock.callHistory.calls(
+ `path:/api/notification/${notificationId}`,
+ );
+ expect(calls.length).toBe(1);
+
+ const subscription = JSON.parse(String(calls[0].options?.body))
+ .subscriptions[0];
+
+ expect(subscription.id).toBe(subscriptionId);
+ expect(subscription.notification_id).toBe(notificationId);
+ expect(subscription.cron_schedule).toBe("0 0 10 * * ? *");
+ expect(subscription.ui_display_type).toBe("cron/builder");
+ });
+
const OWNER_BLOCK_TITLE = /who owns this alert\?/i;
it("should not show the owner picker when creating a new alert", async () => {
@@ -532,8 +635,7 @@ describe("CreateOrEditQuestionAlertModal", () => {
await waitFor(async () => {
const requestBody = await calls[0].options?.body;
- // Unjustified type cast. FIXME
- expect(JSON.parse(requestBody as string).creator_id).toBe(7);
+ expect(JSON.parse(String(requestBody)).creator_id).toBe(7);
});
});
});
diff --git a/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/components/NotificationSchedule/NotificationSchedule.tsx b/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/components/NotificationSchedule/NotificationSchedule.tsx
index 4e9b25ec342..68056f5b581 100644
--- a/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/components/NotificationSchedule/NotificationSchedule.tsx
+++ b/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/components/NotificationSchedule/NotificationSchedule.tsx
@@ -1,14 +1,22 @@
-import { type HTMLAttributes, useCallback, useMemo } from "react";
+import { type HTMLAttributes, useCallback, useMemo, useState } from "react";
import { c, t } from "ttag";
import { Schedule } from "metabase/common/components/Schedule/Schedule";
import {
- cronToScheduleSettings,
+ cronToBuilderValue,
cronUnitToNumber,
isRepeatingEvery,
} from "metabase/common/components/Schedule/cron";
+import type {
+ CronString,
+ ScheduleBuilderValue,
+ ScheduleChangeEvent,
+ ScheduleValue,
+ ScheduleValueType,
+} from "metabase/common/components/Schedule/types";
+import { isScheduleCronValue } from "metabase/common/components/Schedule/types";
+import { getScheduleDefaultsWithoutHour } from "metabase/common/components/Schedule/utils";
import {
- DEFAULT_ALERT_CRON_SCHEDULE,
DEFAULT_ALERT_SCHEDULE,
formatNotificationScheduleDescription,
} from "metabase/notifications/utils";
@@ -17,23 +25,19 @@ import { getApplicationName } from "metabase/selectors/whitelabel";
import { getSetting } from "metabase/settings";
import { Box, type BoxProps, Flex, Text } from "metabase/ui";
import { getScheduleExplanation } from "metabase/utils/cron";
-import type {
- NotificationCronSubscription,
- ScheduleSettings,
- ScheduleType,
-} from "metabase-types/api";
+import type { NotificationCronSubscription } from "metabase-types/api";
import styles from "./NotificationSchedule.module.css";
import { NotificationScheduleWarning } from "./NotificationScheduleWarning";
export interface NotificationScheduleProps {
- subscription?: NotificationCronSubscription;
- scheduleOptions: ScheduleType[];
- onScheduleChange: (subscription: NotificationCronSubscription) => void;
+ initialSubscription?: NotificationCronSubscription;
+ scheduleOptions: ScheduleValueType[];
+ onScheduleChange: (subscription?: NotificationCronSubscription) => void;
}
export const NotificationSchedule = ({
- subscription,
+ initialSubscription,
scheduleOptions,
onScheduleChange,
...boxProps
@@ -42,16 +46,16 @@ export const NotificationSchedule = ({
getSetting(state, "report-timezone-short"),
);
- const scheduleSettings = useMemo(() => {
- return (
- cronToScheduleSettings(
- subscription?.cron_schedule,
- subscription?.ui_display_type === "cron/raw",
- ) || DEFAULT_ALERT_SCHEDULE
- );
- }, [subscription?.cron_schedule, subscription?.ui_display_type]);
-
- const cronString = subscription?.cron_schedule || DEFAULT_ALERT_CRON_SCHEDULE;
+ const [value, setValue] = useState<ScheduleValue>(() => {
+ if (!initialSubscription) {
+ return { ...DEFAULT_ALERT_SCHEDULE };
+ }
+ const { ui_display_type, cron_schedule } = initialSubscription;
+ if (ui_display_type === "cron/raw") {
+ return { schedule_type: "cron", cron: cron_schedule };
+ }
+ return cronToBuilderValue(cron_schedule) ?? { ...DEFAULT_ALERT_SCHEDULE };
+ });
const actionText = t`Alerts will be sent`;
const applicationName = useSelector(getApplicationName);
@@ -59,15 +63,14 @@ export const NotificationSchedule = ({
// No description is necessary for schedule types, which recur periodically.
const PERIODIC_SCHEDULE_TYPES = ["every_n_minutes", "hourly"];
return function ScheduleDescription(
- schedule: ScheduleSettings,
+ value: ScheduleValue,
cronExpression: string,
) {
- // Unjustified type cast. FIXME
- if (PERIODIC_SCHEDULE_TYPES.includes(schedule.schedule_type as string)) {
+ if (PERIODIC_SCHEDULE_TYPES.includes(value.schedule_type)) {
return null;
}
- if (schedule.schedule_type === "cron") {
+ if (isScheduleCronValue(value)) {
return (
<Text className={styles.customScheduleExplainer}>
{`${actionText} ${getScheduleExplanation(cronExpression)}${c("An additional clarification for a human-readable schedule description").t`, according to your ${applicationName} timezone (${timezone}).`}`}
@@ -75,8 +78,7 @@ export const NotificationSchedule = ({
);
}
- const scheduleDescription =
- formatNotificationScheduleDescription(schedule);
+ const scheduleDescription = formatNotificationScheduleDescription(value);
if (!scheduleDescription) {
return null;
}
@@ -94,17 +96,22 @@ export const NotificationSchedule = ({
}, [actionText, applicationName, timezone]);
const handleScheduleChange = useCallback(
- (newCronString: string, newSchedule: ScheduleSettings) => {
- if (subscription) {
- onScheduleChange({
- ...subscription,
- cron_schedule: newCronString,
- ui_display_type:
- newSchedule.schedule_type === "cron" ? "cron/raw" : "cron/builder",
- });
- }
+ ({ value: nextValue, cronString }: ScheduleChangeEvent) => {
+ setValue(nextValue);
+ onScheduleChange(
+ cronString
+ ? {
+ type: "notification-subscription/cron",
+ event_name: null,
+ cron_schedule: cronString,
+ ui_display_type: isScheduleCronValue(nextValue)
+ ? "cron/raw"
+ : "cron/builder",
+ }
+ : undefined,
+ );
},
- [subscription, onScheduleChange],
+ [onScheduleChange],
);
return (
@@ -112,10 +119,10 @@ export const NotificationSchedule = ({
<Flex className={styles.scheduleContainer} direction="column" gap="md">
<Schedule
verb={c("A verb in the imperative mood").t`Check`}
- cronString={cronString}
+ value={value}
scheduleOptions={scheduleOptions}
minutesOnHourPicker
- isCustomSchedule={subscription?.ui_display_type === "cron/raw"}
+ getDefaults={getScheduleDefaultsWithoutHour}
renderScheduleDescription={renderScheduleDescription}
onScheduleChange={handleScheduleChange}
aria-label={t`Describe how often the alert notification should be sent`}
@@ -123,32 +130,30 @@ export const NotificationSchedule = ({
className={styles.schedule}
/>
</Flex>
- {showWarning(scheduleSettings, cronString) && (
- <NotificationScheduleWarning />
- )}
+ {showWarning(value) && <NotificationScheduleWarning />}
</Box>
);
};
-const UNSAFE_SCHEDULE_TYPES = ["every_n_minutes", "cron"];
const WARNING_THRESHOLD_MINS = 10;
-function showWarning(schedule: ScheduleSettings, cronString?: string) {
- if (
- !schedule.schedule_type ||
- !UNSAFE_SCHEDULE_TYPES.includes(schedule.schedule_type) ||
- !schedule.schedule_minute
- ) {
- return false;
- }
- if (schedule.schedule_type === "every_n_minutes") {
- return schedule.schedule_minute < WARNING_THRESHOLD_MINS;
- }
- if (schedule.schedule_type === "cron") {
- const [, minute] = cronString?.split(" ") || [];
- return (
- isRepeatingEvery(minute) &&
- cronUnitToNumber(minute) < WARNING_THRESHOLD_MINS
- );
- }
- return false;
-}
+
+const showWarning = (value: ScheduleValue) =>
+ isScheduleCronValue(value)
+ ? isCronRepeatingTooOften(value.cron)
+ : isBuilderRepeatingTooOften(value);
+
+const isCronRepeatingTooOften = (cron: CronString) => {
+ const [, minute] = cron.split(" ");
+ return (
+ isRepeatingEvery(minute) &&
+ cronUnitToNumber(minute) < WARNING_THRESHOLD_MINS
+ );
+};
+
+const isBuilderRepeatingTooOften = ({
+ schedule_type,
+ schedule_minute,
+}: ScheduleBuilderValue) =>
+ schedule_type === "every_n_minutes" &&
+ !!schedule_minute &&
+ schedule_minute < WARNING_THRESHOLD_MINS;
diff --git a/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/components/NotificationSchedule/NotificationSchedule.unit.spec.tsx b/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/components/NotificationSchedule/NotificationSchedule.unit.spec.tsx
index 38763a51981..9d56b76f208 100644
--- a/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/components/NotificationSchedule/NotificationSchedule.unit.spec.tsx
+++ b/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/components/NotificationSchedule/NotificationSchedule.unit.spec.tsx
@@ -3,68 +3,55 @@ import type { ScheduleDisplayType } from "metabase-types/api";
import { setup } from "./setup.spec";
+const UI_DISPLAY_TYPES: ScheduleDisplayType[] = ["cron/builder", "cron/raw"];
+
+const SKIP_WARNING =
+ /If an alert is still in progress when the next one is scheduled, the next alert will be skipped/;
+
+const setupSchedule = (
+ cronSchedule: string,
+ uiDisplayType: ScheduleDisplayType = "cron/raw",
+) =>
+ setup({
+ subscription: {
+ id: 1,
+ notification_id: 1,
+ type: "notification-subscription/cron",
+ event_name: null,
+ cron_schedule: cronSchedule,
+ created_at: "2025-03-14T16:11:12Z",
+ ui_display_type: uiDisplayType,
+ },
+ });
+
describe("NotificationSchedule", () => {
it("raw - should correctly parse day of week from cron expression", () => {
// In Quartz cron format, days are 1-based: 1=SUN, 2=MON, ..., 7=SAT
// "0 0 9 ? * 2,4,6 *" means Monday, Wednesday, Friday at 9:00 AM
- setup({
- subscription: {
- id: 1,
- notification_id: 1,
- type: "notification-subscription/cron",
- event_name: null,
- cron_schedule: "0 0 9 ? * 2,4,6 *",
- created_at: "2025-03-14T16:11:12Z",
- ui_display_type: "cron/raw",
- },
- });
+ setupSchedule("0 0 9 ? * 2,4,6 *");
expect(
screen.getByText(/Monday, Wednesday, and Friday/),
).toBeInTheDocument();
});
- ["builder", "raw"].forEach((uiDisplayType) => {
+ UI_DISPLAY_TYPES.forEach((uiDisplayType) => {
it(`${uiDisplayType} - should show warning when notification schedule is set to less than 10 minutes`, () => {
- setup({
- subscription: {
- id: 1,
- notification_id: 1,
- type: "notification-subscription/cron",
- event_name: null,
- cron_schedule: "0 0/5 * * * ? *", // every 5 minutes
- created_at: "2025-03-14T16:11:12Z",
- // Unjustified type cast. FIXME
- ui_display_type: `cron/${uiDisplayType}` as ScheduleDisplayType,
- },
- });
+ setupSchedule("0 0/5 * * * ? *", uiDisplayType);
- expect(
- screen.getByText(
- /If an alert is still in progress when the next one is scheduled, the next alert will be skipped/,
- ),
- ).toBeInTheDocument();
+ expect(screen.getByText(SKIP_WARNING)).toBeInTheDocument();
});
it(`${uiDisplayType} - should not show warning when notification schedule is set to 10 or more minutes`, () => {
- setup({
- subscription: {
- id: 1,
- notification_id: 1,
- type: "notification-subscription/cron",
- event_name: null,
- cron_schedule: "0 0/10 * * * ? *", // every 10 minutes
- created_at: "2025-03-14T16:11:12Z",
- // Unjustified type cast. FIXME
- ui_display_type: `cron/${uiDisplayType}` as ScheduleDisplayType,
- },
- });
+ setupSchedule("0 0/10 * * * ? *", uiDisplayType);
- expect(
- screen.queryByText(
- /If an alert is still in progress when the next one is scheduled, the next alert will be skipped/,
- ),
- ).not.toBeInTheDocument();
+ expect(screen.queryByText(SKIP_WARNING)).not.toBeInTheDocument();
});
});
+
+ it("raw - should not show warning when a custom schedule runs at a fixed minute", () => {
+ setupSchedule("0 0 8 * * ? *");
+
+ expect(screen.queryByText(SKIP_WARNING)).not.toBeInTheDocument();
+ });
});
diff --git a/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/components/NotificationSchedule/setup.spec.tsx b/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/components/NotificationSchedule/setup.spec.tsx
index 2fc66195252..6cce9951334 100644
--- a/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/components/NotificationSchedule/setup.spec.tsx
+++ b/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/components/NotificationSchedule/setup.spec.tsx
@@ -1,10 +1,8 @@
import { mockSettings } from "__support__/settings";
import { renderWithProviders } from "__support__/ui";
+import type { ScheduleValueType } from "metabase/common/components/Schedule/types";
import { createMockState } from "metabase/redux/store/mocks";
-import type {
- NotificationCronSubscription,
- ScheduleType,
-} from "metabase-types/api";
+import type { NotificationCronSubscription } from "metabase-types/api";
import { NotificationSchedule } from "./NotificationSchedule";
@@ -12,7 +10,17 @@ interface SetupOpts {
subscription?: NotificationCronSubscription;
}
-const mockScheduleOptions: ScheduleType[] = [
+const mockSubscription: NotificationCronSubscription = {
+ id: 1,
+ notification_id: 1,
+ type: "notification-subscription/cron",
+ event_name: null,
+ cron_schedule: "0 0 8 * * ? *",
+ created_at: "2025-03-14T16:11:12Z",
+ ui_display_type: "cron/builder",
+};
+
+const mockScheduleOptions: ScheduleValueType[] = [
"every_n_minutes",
"hourly",
"daily",
@@ -22,7 +30,7 @@ const mockScheduleOptions: ScheduleType[] = [
const mockOnScheduleChange = jest.fn();
-export const setup = ({ subscription }: SetupOpts = {}) => {
+export const setup = ({ subscription = mockSubscription }: SetupOpts = {}) => {
const state = createMockState({
settings: mockSettings({
"report-timezone-short": "UTC",
@@ -32,7 +40,7 @@ export const setup = ({ subscription }: SetupOpts = {}) => {
const props = {
scheduleOptions: mockScheduleOptions,
onScheduleChange: mockOnScheduleChange,
- subscription,
+ initialSubscription: subscription,
};
renderWithProviders(<NotificationSchedule {...props} />, {
diff --git a/frontend/src/metabase/notifications/utils.ts b/frontend/src/metabase/notifications/utils.ts
index 0d591124ca6..1fd596133e3 100644
--- a/frontend/src/metabase/notifications/utils.ts
+++ b/frontend/src/metabase/notifications/utils.ts
@@ -1,7 +1,13 @@
import { c, msgid, ngettext, t } from "ttag";
import _ from "underscore";
-import { cronToScheduleSettings } from "metabase/common/components/Schedule/cron";
+import { cronToBuilderValue } from "metabase/common/components/Schedule/cron";
+import type {
+ ScheduleBuilderValue,
+ ScheduleValue,
+} from "metabase/common/components/Schedule/types";
+import { isScheduleCronValue } from "metabase/common/components/Schedule/types";
+import { getScheduleDefaultsWithoutHour } from "metabase/common/components/Schedule/utils";
import type { NotificationListItem } from "metabase/notifications/types";
import { getScheduleExplanation } from "metabase/utils/cron";
import { getEmailDomain, isEmail } from "metabase/utils/email";
@@ -28,7 +34,6 @@ import type {
NotificationHandlerSlack,
NotificationRecipient,
NotificationRecipientRawValue,
- ScheduleSettings,
UpdateAlertNotificationRequest,
User,
UserId,
@@ -37,13 +42,9 @@ import type {
import type { NotificationTriggerOption } from "./modals/CreateOrEditQuestionAlertModal/types";
-export const DEFAULT_ALERT_CRON_SCHEDULE = "0 0 8 * * ? *";
-export const DEFAULT_ALERT_SCHEDULE: ScheduleSettings = {
+export const DEFAULT_ALERT_SCHEDULE: ScheduleBuilderValue = {
schedule_type: "daily",
- schedule_day: null,
- schedule_frame: null,
- schedule_hour: 8,
- schedule_minute: 0,
+ ...getScheduleDefaultsWithoutHour("daily"),
};
const getDefaultChannelConfig = ({
@@ -135,14 +136,8 @@ export const getDefaultQuestionAlertRequest = ({
currentUserId,
userCanAccessSettings,
}),
- subscriptions: [
- {
- type: "notification-subscription/cron",
- event_name: null,
- cron_schedule: DEFAULT_ALERT_CRON_SCHEDULE,
- ui_display_type: "cron/builder",
- },
- ],
+ // A new alert has no subscription until the user picks a time
+ subscriptions: [],
};
};
@@ -267,6 +262,7 @@ export function alertIsValid(
return (
channelSpec?.channels &&
+ notification.subscriptions.length > 0 &&
handlers.length > 0 &&
handlers.every((handlers) => channelIsValid(handlers)) &&
handlers.every((c) => {
@@ -369,29 +365,40 @@ export const getNotificationHandlersGroupedByTypes = (
export const formatNotificationSchedule = (
subscription: NotificationCronSubscription,
): string | null => {
- const schedule = cronToScheduleSettings(
- subscription.cron_schedule,
- subscription.ui_display_type === "cron/raw",
- );
+ const value: ScheduleValue | null =
+ subscription.ui_display_type === "cron/raw"
+ ? { schedule_type: "cron", cron: subscription.cron_schedule }
+ : cronToBuilderValue(subscription.cron_schedule);
return (
- (schedule &&
- formatNotificationCheckSchedule(schedule, subscription.cron_schedule)) ||
+ (value &&
+ formatNotificationCheckSchedule(value, subscription.cron_schedule)) ||
null
);
};
export const formatNotificationCheckSchedule = (
- {
+ value: ScheduleValue,
+ cronSchedule: string,
+) => {
+ const options = MetabaseSettings.formattingOptions();
+
+ if (isScheduleCronValue(value)) {
+ const explanation = getScheduleExplanation(cronSchedule);
+ return explanation
+ ? c(
+ "{0} is a human-readable schedule description, e.g. 'every day at 8:00 AM'",
+ ).t`Check ${explanation}`
+ : null;
+ }
+
+ const {
schedule_type,
schedule_minute,
schedule_hour,
schedule_day,
schedule_frame,
- }: ScheduleSettings,
- cronSchedule: string,
-) => {
- const options = MetabaseSettings.formattingOptions();
+ } = value;
switch (schedule_type) {
case "every_n_minutes":
@@ -430,12 +437,6 @@ export const formatNotificationCheckSchedule = (
}
break;
}
- case "cron":
- try {
- return t`Check ${getScheduleExplanation(cronSchedule)}`;
- } catch {
- return null;
- }
}
return null;
@@ -444,7 +445,7 @@ export const formatNotificationCheckSchedule = (
export const formatNotificationScheduleDescription = ({
schedule_type,
schedule_hour,
-}: ScheduleSettings) => {
+}: ScheduleBuilderValue) => {
switch (schedule_type) {
case "daily":
case "weekly":
diff --git a/frontend/src/metabase/pulse/pulse.ts b/frontend/src/metabase/pulse/pulse.ts
index e7b45dc9731..07a07f3e32e 100644
--- a/frontend/src/metabase/pulse/pulse.ts
+++ b/frontend/src/metabase/pulse/pulse.ts
@@ -34,27 +34,31 @@ export const NEW_PULSE_TEMPLATE = {
parameters: [],
} satisfies Partial<DashboardSubscription>;
-export function channelIsValid(channel: Channel, channelSpec?: ChannelSpec) {
+export const channelTargetIsValid = (
+ channel: Channel,
+ channelSpec?: ChannelSpec,
+) => {
switch (channel.channel_type) {
case "email":
- return (
+ return Boolean(
channel.recipients &&
channel.recipients.length > 0 &&
channel.recipients.every(recipientIsValid) &&
- fieldsAreValid(channel, channelSpec) &&
- scheduleIsValid(channel)
+ fieldsAreValid(channel, channelSpec),
);
case "slack":
- return (
- channel.details?.channel &&
- fieldsAreValid(channel, channelSpec) &&
- scheduleIsValid(channel)
+ return Boolean(
+ channel.details?.channel && fieldsAreValid(channel, channelSpec),
);
case "http":
- return channel.channel_id && scheduleIsValid(channel);
+ return Boolean(channel.channel_id);
default:
return false;
}
+};
+
+export function channelIsValid(channel: Channel, channelSpec?: ChannelSpec) {
+ return channelTargetIsValid(channel, channelSpec) && scheduleIsValid(channel);
}
export function scheduleIsValid(channel: Channel) {
@@ -136,23 +140,20 @@ export function dashboardPulseIsValid(
export function cleanPulse<T extends DashboardSubscriptionData>(
pulse: T,
channelSpecs: Partial<ChannelSpecs>,
+ includingSubscription: boolean = true,
): T {
+ const shouldKeepChannel = includingSubscription
+ ? channelIsValid
+ : channelTargetIsValid;
return {
...pulse,
- channels: cleanPulseChannels(pulse.channels, channelSpecs),
+ channels: pulse.channels.filter((channel) =>
+ shouldKeepChannel(channel, channelSpecs?.[channel.channel_type]),
+ ),
parameters: cleanPulseParameters(getPulseParameters(pulse)),
};
}
-function cleanPulseChannels(
- channels: Channel[],
- channelSpecs: Partial<ChannelSpecs>,
-) {
- return channels.filter((channel) =>
- channelIsValid(channel, channelSpecs?.[channel.channel_type]),
- );
-}
-
function cleanPulseParameters(parameters: Parameter[]) {
return parameters.map((parameter) => {
const { default: defaultValue, name, slug, type, value, id } = parameter;
diff --git a/frontend/src/metabase/transforms/components/JobEditor/ScheduleSection/ScheduleSection.tsx b/frontend/src/metabase/transforms/components/JobEditor/ScheduleSection/ScheduleSection.tsx
index 20aba6f9059..cd196bb76be 100644
--- a/frontend/src/metabase/transforms/components/JobEditor/ScheduleSection/ScheduleSection.tsx
+++ b/frontend/src/metabase/transforms/components/JobEditor/ScheduleSection/ScheduleSection.tsx
@@ -6,18 +6,24 @@ import {
useRunTransformJobMutation,
} from "metabase/api";
import { ConfirmModal } from "metabase/common/components/ConfirmModal";
-import { Schedule } from "metabase/common/components/Schedule";
+import {
+ Schedule,
+ cronToBuilderValue,
+} from "metabase/common/components/Schedule";
+import type {
+ ScheduleBuilderValue,
+ ScheduleChangeEvent,
+ ScheduleValue,
+ ScheduleValueType,
+} from "metabase/common/components/Schedule/types";
+import { isScheduleCronValue } from "metabase/common/components/Schedule/types";
import { TitleSection } from "metabase/common/data-studio/components/TitleSection";
import { useMetadataToasts } from "metabase/metadata/hooks";
import { useSetting } from "metabase/settings";
import { Box, Divider, Group, Tooltip } from "metabase/ui";
import { getScheduleExplanation } from "metabase/utils/cron";
import { isResourceNotFoundError } from "metabase/utils/errors";
-import type {
- ScheduleDisplayType,
- ScheduleSettings,
- ScheduleType,
-} from "metabase-types/api";
+import type { ScheduleDisplayType } from "metabase-types/api";
import { trackTransformJobTriggerManualRun } from "../../../analytics";
import { RunButton } from "../../RunButton";
@@ -74,7 +80,7 @@ type ScheduleWidgetProps = {
) => void;
};
-const SCHEDULE_OPTIONS: ScheduleType[] = [
+const SCHEDULE_OPTIONS: ScheduleValueType[] = [
"hourly",
"daily",
"weekly",
@@ -82,19 +88,24 @@ const SCHEDULE_OPTIONS: ScheduleType[] = [
"cron",
];
+const DEFAULT_SETTINGS: ScheduleBuilderValue = {
+ schedule_type: "hourly",
+ schedule_minute: 0,
+};
+
function ScheduleWidget({ job, onChangeSchedule }: ScheduleWidgetProps) {
const verb = c("A verb in the imperative mood").t`Run`;
const systemTimezone = useSetting("system-timezone") ?? "UTC";
const renderScheduleDescription = (
- settings: ScheduleSettings,
- schedule: string,
+ value: ScheduleValue,
+ cronString: string,
) => {
- if (settings.schedule_type !== "cron") {
+ if (!isScheduleCronValue(value)) {
return null;
}
- const scheduleExplanation = getScheduleExplanation(schedule);
+ const scheduleExplanation = getScheduleExplanation(cronString);
if (scheduleExplanation == null) {
return null;
}
@@ -102,21 +113,28 @@ function ScheduleWidget({ job, onChangeSchedule }: ScheduleWidgetProps) {
return t`This job will run ${scheduleExplanation}, ${systemTimezone}`;
};
- const handleChange = (schedule: string, settings: ScheduleSettings) => {
+ const value: ScheduleValue =
+ job.ui_display_type === "cron/raw"
+ ? { schedule_type: "cron", cron: job.schedule }
+ : (cronToBuilderValue(job.schedule) ?? DEFAULT_SETTINGS);
+
+ const handleChange = ({ value, cronString }: ScheduleChangeEvent) => {
+ if (!cronString) {
+ return;
+ }
onChangeSchedule(
- schedule,
- settings.schedule_type === "cron" ? "cron/raw" : "cron/builder",
+ cronString,
+ isScheduleCronValue(value) ? "cron/raw" : "cron/builder",
);
};
return (
<Schedule
- cronString={job.schedule}
+ value={value}
scheduleOptions={SCHEDULE_OPTIONS}
verb={verb}
timezone={systemTimezone}
layout="horizontal"
- isCustomSchedule={job.ui_display_type === "cron/raw"}
renderScheduleDescription={renderScheduleDescription}
data-testid="schedule-picker"
onScheduleChange={handleChange}