Skip to content

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

Carry over picked schedule fields when the frequency changes (#80758)

Egor Grushin2459fe20baa4
diff --git a/frontend/src/metabase/common/components/Schedule/Schedule.stories.tsx b/frontend/src/metabase/common/components/Schedule/Schedule.stories.tsx
index 47076ee4b4d..4f38394c379 100644
--- a/frontend/src/metabase/common/components/Schedule/Schedule.stories.tsx
+++ b/frontend/src/metabase/common/components/Schedule/Schedule.stories.tsx
@@ -13,7 +13,7 @@ import { createMockState } from "metabase/redux/store/mocks";
import { Schedule } from "./Schedule";
import { cronToBuilderValue } from "./cron";
-import type { ScheduleValue } from "./types";
+import type { ScheduleValue } from "./domain";
const storeInitialState = createMockState({
settings: mockSettings(),
diff --git a/frontend/src/metabase/common/components/Schedule/Schedule.tsx b/frontend/src/metabase/common/components/Schedule/Schedule.tsx
index 081e90195c3..5b7a9476b94 100644
--- a/frontend/src/metabase/common/components/Schedule/Schedule.tsx
+++ b/frontend/src/metabase/common/components/Schedule/Schedule.tsx
@@ -6,7 +6,6 @@ import { c } from "ttag";
import { CronExpressionInput } from "metabase/common/components/CronExpressioInput";
import { Box, Flex, type FlexProps } from "metabase/ui";
import { formatCronExpressionForUI } from "metabase/utils/cron";
-import type { ScheduleSettings } from "metabase-types/api";
import {
GROUP_ATTRIBUTES,
@@ -22,23 +21,20 @@ import {
SelectWeekdayOfMonth,
} from "./components";
import { scheduleValueToCron, toScheduleBuilderValue } from "./cron";
-import { byTheMinuteIntervals } from "./strings";
-import type {
- ScheduleBuilderValue,
- ScheduleChangeEvent,
- ScheduleValue,
- ScheduleValueType,
- UpdateSchedule,
-} from "./types";
-import { isScheduleCronValue } from "./types";
import {
type GetScheduleDefaults,
- clearDayForMidFrame,
+ type NormalizedScheduleValue,
+ type ScheduleValue,
+ type ScheduleValueType,
+ changeScheduleType,
getScheduleDefaults,
isScheduleComplete,
+ isScheduleCronValue,
normalizeScheduleValue,
- resetScheduleToTypeDefaults,
-} from "./utils";
+ setScheduleField,
+} from "./domain";
+import { byTheMinuteIntervals } from "./strings";
+import type { ScheduleChangeEvent, UpdateSchedule } from "./types";
export interface ScheduleProps {
className?: string;
@@ -53,7 +49,7 @@ export interface ScheduleProps {
layout?: "vertical" | "horizontal";
fullWidthSelects?: boolean;
renderScheduleDescription?: (
- value: ScheduleValue,
+ value: NormalizedScheduleValue,
cronInputValue: string,
) => JSX.Element | string | null;
}
@@ -73,7 +69,7 @@ export const Schedule = ({
renderScheduleDescription,
...flexProps
}: ScheduleProps & FlexProps & HTMLAttributes<HTMLDivElement>) => {
- const normalizedValue = useMemo<ScheduleValue>(
+ const normalizedValue = useMemo(
() => normalizeScheduleValue(value, getDefaults),
[value, getDefaults],
);
@@ -82,7 +78,7 @@ export const Schedule = ({
);
const emitChange = useCallback(
- (nextValue: ScheduleValue) => {
+ (nextValue: NormalizedScheduleValue) => {
onScheduleChange({
value: nextValue,
cronString: isScheduleComplete(nextValue)
@@ -103,7 +99,7 @@ export const Schedule = ({
}
emitChange(
- resetScheduleToTypeDefaults(
+ changeScheduleType(
toScheduleBuilderValue(normalizedValue),
scheduleType,
getDefaults,
@@ -113,22 +109,6 @@ export const Schedule = ({
[emitChange, getDefaults, normalizedValue],
);
- const createUpdateSchedule = useCallback(
- (schedule: ScheduleBuilderValue): UpdateSchedule =>
- (
- updatedField: keyof ScheduleSettings,
- newValue: ScheduleSettings[typeof updatedField],
- ) => {
- const nextValue: ScheduleBuilderValue = {
- ...schedule,
- [updatedField]: newValue,
- };
-
- emitChange(clearDayForMidFrame(nextValue));
- },
- [emitChange],
- );
-
const renderedSchedule = useMemo(() => {
const selectFrequency = (
<SelectFrequency
@@ -154,7 +134,8 @@ export const Schedule = ({
const { schedule_frame, schedule_day, schedule_hour, schedule_minute } =
normalizedValue;
- const updateSchedule = createUpdateSchedule(normalizedValue);
+ const updateSchedule: UpdateSchedule = (field, value) =>
+ emitChange(setScheduleField(normalizedValue, field, value));
const selectMinute = (
<SelectMinute
@@ -269,7 +250,6 @@ export const Schedule = ({
normalizedValue,
scheduleOptions,
timezone,
- createUpdateSchedule,
updateScheduleType,
verb,
cronInputValue,
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 cbf84321b90..c7a96eb0958 100644
--- a/frontend/src/metabase/common/components/Schedule/Schedule.unit.spec.tsx
+++ b/frontend/src/metabase/common/components/Schedule/Schedule.unit.spec.tsx
@@ -383,12 +383,6 @@ describe("Schedule", () => {
"0 0 15 1 * ? *",
],
// Default-filling when only the frequency changes
- [
- "switch daily to weekly defaults to Monday",
- "0 0 8 * * ? *",
- { frequency: "weekly" },
- "0 0 8 ? * 2 *",
- ],
[
"switch daily to monthly defaults to first of month",
"0 0 8 * * ? *",
@@ -396,10 +390,28 @@ describe("Schedule", () => {
"0 0 8 1 * ? *",
],
[
- "switch weekly to monthly drops the weekday",
+ "switch weekly to monthly keeps the weekday",
"0 0 8 ? * 6 *",
{ frequency: "monthly" },
- "0 0 8 1 * ? *",
+ "0 0 8 ? * 6#1 *",
+ ],
+ [
+ "switch weekly to daily keeps the time",
+ "0 0 20 ? * 6 *",
+ { frequency: "daily" },
+ "0 0 20 * * ? *",
+ ],
+ [
+ "switch daily loaded from a cron with a hidden minute to weekly defaults to Monday, keeps the hour and drops the minute",
+ "0 30 15 * * ? *",
+ { frequency: "weekly" },
+ "0 0 15 ? * 2 *",
+ ],
+ [
+ "changing the time on a daily loaded from a cron with a hidden minute drops the minute",
+ "0 30 15 * * ? *",
+ { time: "10:00" },
+ "0 0 22 * * ? *",
],
[
"switch monthly to daily clears frame and weekday",
@@ -453,6 +465,33 @@ describe("Schedule", () => {
},
);
+ it("does not carry a minute past the hour into a type that hides it", async () => {
+ const { onScheduleChange } = setup({
+ value: scheduleFromCron("0 0 * * * ? *"),
+ minutesOnHourPicker: true,
+ });
+
+ await pickField("minute", "15");
+ await pickField("frequency", "daily");
+
+ expect(screen.queryByTestId("select-minute")).not.toBeInTheDocument();
+ const lastEvent = checkNotNull(onScheduleChange.mock.calls.at(-1))[0];
+ expect(lastEvent.cronString).toBe("0 0 8 * * ? *");
+ });
+
+ it("does not carry a minute named by a custom cron expression into a type that hides it", async () => {
+ const { onScheduleChange } = setup({
+ value: { schedule_type: "cron", cron: "0 15 8 * * ? *" },
+ });
+
+ await pickField("frequency", "daily");
+
+ expect(screen.getByTestId("select-time")).toHaveValue("8:00");
+ expectAmPmToBe("AM");
+ const lastEvent = checkNotNull(onScheduleChange.mock.calls.at(-1))[0];
+ expect(lastEvent.cronString).toBe("0 0 8 * * ? *");
+ });
+
it("keeps the day of the month a custom cron expression names", async () => {
setup({ value: { schedule_type: "cron", cron: "0 0 8 15 * ? *" } });
@@ -462,9 +501,9 @@ describe("Schedule", () => {
});
describe("with defaults that supply no hour", () => {
- it("leaves the time unpicked when coming from a custom cron expression", async () => {
+ it("leaves the time unpicked when the previous type had no time", async () => {
const { onScheduleChange } = setup({
- value: { schedule_type: "cron", cron: "0 0 15 1 * ? *" },
+ value: { schedule_type: "cron", cron: "0 0 * * * ? *" },
getDefaults: getDefaultsWithoutHour,
});
@@ -476,18 +515,18 @@ describe("Schedule", () => {
expect(lastEvent.cronString).toBeNull();
});
- it("unpicks the time the user had picked on the previous type", async () => {
+ it("keeps the time a custom cron expression named", async () => {
const { onScheduleChange } = setup({
- value: scheduleFromCron("0 0 20 * * ? *"),
+ value: { schedule_type: "cron", cron: "0 0 15 1 * ? *" },
getDefaults: getDefaultsWithoutHour,
});
- await pickField("frequency", "weekly");
+ await pickField("frequency", "daily");
- expect(screen.getByTestId("select-time")).toHaveValue("");
- expectAmPmToBe("AM");
+ expect(screen.getByTestId("select-time")).toHaveValue("3:00");
+ expectAmPmToBe("PM");
const lastEvent = checkNotNull(onScheduleChange.mock.calls.at(-1))[0];
- expect(lastEvent.cronString).toBeNull();
+ expect(lastEvent.cronString).toBe("0 0 15 * * ? *");
});
it("lets the user pick AM/PM before the time, without picking a time for them", async () => {
diff --git a/frontend/src/metabase/common/components/Schedule/components.tsx b/frontend/src/metabase/common/components/Schedule/components.tsx
index 3634d17568f..125fa486766 100644
--- a/frontend/src/metabase/common/components/Schedule/components.tsx
+++ b/frontend/src/metabase/common/components/Schedule/components.tsx
@@ -16,6 +16,7 @@ import type {
import { AutoWidthSelect } from "./AutoWidthSelect";
import { AM, PM } from "./constants";
import { hourTo24HourFormat, hourToTwelveHourFormat } from "./cron";
+import type { ScheduleValueType } from "./domain";
import {
type Weekday,
getHours,
@@ -23,7 +24,7 @@ import {
getScheduleStrings,
minutes,
} from "./strings";
-import type { AmPm, ScheduleValueType, UpdateSchedule } from "./types";
+import type { AmPm, UpdateSchedule } from "./types";
export type SelectFrameProps = {
schedule_frame: ScheduleSettings["schedule_frame"];
@@ -230,12 +231,14 @@ export const SelectMinute = ({
updateSchedule: UpdateSchedule;
range?: typeof minutes;
}) => {
- // Unjustified type cast. FIXME
- const minuteOfHour = isNaN(schedule_minute as number) ? 0 : schedule_minute;
+ const minuteOfHour =
+ isNotNull(schedule_minute) && !Number.isNaN(schedule_minute)
+ ? schedule_minute
+ : 0;
const label = useMemo(() => getScheduleComponentLabel("minute"), []);
return (
<AutoWidthSelect
- value={(minuteOfHour || 0).toString()}
+ value={minuteOfHour.toString()}
data={range}
onChange={(value: string) =>
updateSchedule("schedule_minute", Number(value))
diff --git a/frontend/src/metabase/common/components/Schedule/constants.ts b/frontend/src/metabase/common/components/Schedule/constants.ts
index 9df552cdaa0..3f418f345d7 100644
--- a/frontend/src/metabase/common/components/Schedule/constants.ts
+++ b/frontend/src/metabase/common/components/Schedule/constants.ts
@@ -1,5 +1,2 @@
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 b1d9f98b159..85a320b38bf 100644
--- a/frontend/src/metabase/common/components/Schedule/cron.ts
+++ b/frontend/src/metabase/common/components/Schedule/cron.ts
@@ -7,16 +7,16 @@ import type {
} from "metabase-types/api";
import { PM } from "./constants";
-import { Cron, getScheduleStrings } from "./strings";
import type {
- AmPm,
CronString,
+ NormalizedScheduleValue,
ScheduleBuilderType,
ScheduleBuilderValue,
ScheduleValue,
-} from "./types";
-import { isScheduleCronValue } from "./types";
-import { clearUnusedScheduleFields } from "./utils";
+} from "./domain";
+import { isScheduleCronValue } from "./domain";
+import { Cron, getScheduleStrings } from "./strings";
+import type { AmPm } from "./types";
const everyToCronSyntax = (every: number | string) =>
`${Cron.EveryPrefix}${every}`;
@@ -25,6 +25,11 @@ export const isRepeatingEvery = (every: string) =>
export const cronUnitToNumber = (unit: string) =>
parseInt(unit.replace(Cron.EveryPrefix, ""));
+const cronUnitToNumberOrNull = (unit: string) => {
+ const number = cronUnitToNumber(unit);
+ return Number.isNaN(number) ? null : number;
+};
+
const dayToCron = (day: ScheduleSettings["schedule_day"]) => {
const { weekdays } = getScheduleStrings();
const index = weekdays.findIndex((o) => o.value === day);
@@ -94,15 +99,14 @@ const defaultSchedule: ScheduleBuilderValue = {
};
export const defaultCron = formatCron(defaultSchedule);
-export const toCronString = (schedule: ScheduleBuilderValue): CronString =>
- formatCron(clearUnusedScheduleFields(schedule));
-
-export const scheduleValueToCron = (value: ScheduleValue): CronString => {
+export const scheduleValueToCron = (
+ value: NormalizedScheduleValue,
+): CronString => {
if (isScheduleCronValue(value)) {
return value.cron;
}
- return toCronString(value);
+ return formatCron(value);
};
export const cronToBuilderValue_unmemoized = (
@@ -179,8 +183,9 @@ export const cronToBuilderValue_unmemoized = (
}
const scheduleMinute =
- minute === Cron.AllValues ? null : cronUnitToNumber(minute);
- const scheduleHour = hour === Cron.AllValues ? null : cronUnitToNumber(hour);
+ minute === Cron.AllValues ? null : cronUnitToNumberOrNull(minute);
+ const scheduleHour =
+ hour === Cron.AllValues ? null : cronUnitToNumberOrNull(hour);
return {
schedule_type,
schedule_minute: scheduleMinute,
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 4964c0311c6..cad75737adb 100644
--- a/frontend/src/metabase/common/components/Schedule/cron.unit.spec.ts
+++ b/frontend/src/metabase/common/components/Schedule/cron.unit.spec.ts
@@ -5,9 +5,8 @@ import {
hourTo24HourFormat,
hourToTwelveHourFormat,
scheduleValueToCron,
- toCronString,
} from "./cron";
-import type { ScheduleBuilderValue } from "./types";
+import type { ScheduleBuilderValue } from "./domain";
describe("formatCron", () => {
it("converts every_n_minutes schedule to cron", () => {
@@ -94,62 +93,6 @@ describe("formatCron", () => {
});
});
-describe("toCronString", () => {
- it("strips day, frame, and hour for hourly schedules", () => {
- const cron = toCronString({
- schedule_type: "hourly",
- schedule_minute: 30,
- schedule_hour: 8,
- schedule_day: "mon",
- schedule_frame: "first",
- });
- expect(cron).toEqual("0 30 * * * ? *");
- });
-
- it("strips day, frame, and hour for every_n_minutes schedules", () => {
- const cron = toCronString({
- schedule_type: "every_n_minutes",
- schedule_minute: 10,
- schedule_hour: 8,
- schedule_day: "mon",
- schedule_frame: "first",
- });
- expect(cron).toEqual("0 0/10 * * * ? *");
- });
-
- it("keeps hour but strips day and frame for daily schedules", () => {
- const cron = toCronString({
- schedule_type: "daily",
- schedule_minute: 30,
- schedule_hour: 14,
- schedule_day: "mon",
- schedule_frame: "first",
- });
- expect(cron).toEqual("0 30 14 * * ? *");
- });
-
- it("keeps day and hour for weekly schedules", () => {
- const cron = toCronString({
- schedule_type: "weekly",
- schedule_day: "mon",
- schedule_minute: 0,
- schedule_hour: 12,
- });
- expect(cron).toEqual("0 0 12 ? * 2 *");
- });
-
- it("keeps day, frame, and hour for monthly schedules", () => {
- const cron = toCronString({
- schedule_type: "monthly",
- schedule_day: "wed",
- schedule_frame: "first",
- schedule_minute: 15,
- schedule_hour: 9,
- });
- expect(cron).toEqual("0 15 9 ? * 4#1 *");
- });
-});
-
describe("cronToBuilderValue", () => {
it("returns default schedule when input is null or undefined", () => {
const defaultSchedule = {
@@ -264,6 +207,28 @@ describe("cronToBuilderValue", () => {
});
});
+ describe("units it cannot read", () => {
+ it("leaves the hour unpicked when the cron increments it", () => {
+ expect(cronToBuilderValue("0 0 */2 * * ? *")).toEqual(
+ expect.objectContaining({
+ schedule_type: "daily",
+ schedule_minute: 0,
+ schedule_hour: null,
+ }),
+ );
+ });
+
+ it("leaves the minute unpicked when the cron increments it without a start", () => {
+ expect(cronToBuilderValue("0 */5 * * * ? *")).toEqual(
+ expect.objectContaining({
+ schedule_type: "hourly",
+ schedule_minute: null,
+ schedule_hour: null,
+ }),
+ );
+ });
+ });
+
describe("every n minutes schedule determination", () => {
it('sets schedule type to "every_n_minutes" when minute is "0/15"', () => {
const cron = `0 0/15 * * * ?`;
@@ -369,6 +334,8 @@ describe("scheduleValueToCron", () => {
expect(
scheduleValueToCron({
schedule_type: "daily",
+ schedule_day: null,
+ schedule_frame: null,
schedule_hour: null,
schedule_minute: 0,
}),
diff --git a/frontend/src/metabase/common/components/Schedule/domain/index.ts b/frontend/src/metabase/common/components/Schedule/domain/index.ts
new file mode 100644
index 00000000000..cc3f3b29b0a
--- /dev/null
+++ b/frontend/src/metabase/common/components/Schedule/domain/index.ts
@@ -0,0 +1,2 @@
+export * from "./schedule";
+export * from "./types";
diff --git a/frontend/src/metabase/common/components/Schedule/domain/schedule.ts b/frontend/src/metabase/common/components/Schedule/domain/schedule.ts
new file mode 100644
index 00000000000..f983f5ec7e1
--- /dev/null
+++ b/frontend/src/metabase/common/components/Schedule/domain/schedule.ts
@@ -0,0 +1,219 @@
+import _ from "underscore";
+
+import { isNotNull } from "metabase/utils/types";
+
+import type {
+ GetScheduleDefaults,
+ NormalizedScheduleBuilderValue,
+ NormalizedScheduleValue,
+ ScheduleBuilderType,
+ ScheduleBuilderValue,
+ ScheduleCronValue,
+ ScheduleField,
+ ScheduleFields,
+ ScheduleSpecification,
+ ScheduleValue,
+} from "./types";
+
+export const SCHEDULE_FIELDS = [
+ "schedule_day",
+ "schedule_frame",
+ "schedule_hour",
+ "schedule_minute",
+] as const satisfies readonly ScheduleField[];
+
+/**
+ * The single source of truth for the shape of every builder type. The table
+ * exists to state the per-type invariants in one place and to have the code
+ * below maintain and guarantee them: normalizing, changing the type and
+ * setting a field all derive what to keep, reset or clear from this table
+ * rather than from ad-hoc rules, and a value that breaks its type's
+ * invariants is rejected instead of being emitted.
+ *
+ * Each type is described in terms of its fields:
+ *
+ * - `variables` are the fields the user picks in the UI. `unit` names what the
+ * field means for that type, e.g. `schedule_minute` is a minute past the
+ * hour for `hourly` but an interval for `every_n_minutes`. `nullable`
+ * variables may stay unpicked without making the schedule incomplete.
+ * - `constants` are fields the type needs in the cron but never shows, so
+ * they are pinned to a fixed value.
+ * - `defaults` fill in the variables that have no value yet.
+ *
+ * Every other field is `null` for that type.
+ *
+ * When the type changes, a picked variable is carried over only when the new
+ * type has the same variable with the same unit; everything else comes from
+ * the constants and the defaults of the new type. A loaded value keeps a
+ * constant field as is (e.g. a custom cron may hold a daily schedule at 8:30)
+ * so that saving it unchanged does not alter it, but the first edit in the UI
+ * resets it to the constant so that what the UI shows is what the cron says.
+ */
+export const SCHEDULE_SPECIFICATIONS: Record<
+ ScheduleBuilderType,
+ ScheduleSpecification
+> = {
+ every_n_minutes: {
+ variables: { schedule_minute: { unit: "interval", nullable: true } },
+ constants: {},
+ defaults: { schedule_minute: 10 },
+ },
+ hourly: {
+ variables: { schedule_minute: { unit: "minute", nullable: true } },
+ constants: {},
+ defaults: { schedule_minute: 0 },
+ },
+ daily: {
+ variables: { schedule_hour: { unit: "hour" } },
+ constants: { schedule_minute: 0 },
+ defaults: { schedule_hour: 8 },
+ },
+ weekly: {
+ variables: {
+ schedule_day: { unit: "weekday" },
+ schedule_hour: { unit: "hour" },
+ },
+ constants: { schedule_minute: 0 },
+ defaults: { schedule_day: "mon", schedule_hour: 8 },
+ },
+ monthly: {
+ variables: {
+ schedule_frame: { unit: "frame" },
+ schedule_day: { unit: "weekday", nullable: true },
+ schedule_hour: { unit: "hour" },
+ },
+ constants: { schedule_minute: 0 },
+ defaults: {
+ schedule_frame: "first",
+ schedule_day: null,
+ schedule_hour: 8,
+ },
+ },
+};
+
+export const getScheduleDefaults: GetScheduleDefaults = (scheduleType) =>
+ SCHEDULE_SPECIFICATIONS[scheduleType].defaults;
+
+export const isScheduleCronValue = (
+ value: ScheduleValue,
+): value is ScheduleCronValue => value.schedule_type === "cron";
+
+const isNormalizedScheduleBuilderValue = (
+ schedule: ScheduleBuilderValue,
+): schedule is NormalizedScheduleBuilderValue => {
+ const { variables, constants } =
+ SCHEDULE_SPECIFICATIONS[schedule.schedule_type];
+ return SCHEDULE_FIELDS.every((field) => {
+ if (field in variables) {
+ return true;
+ }
+ if (field in constants) {
+ return isNotNull(schedule[field]);
+ }
+ return schedule[field] === null;
+ });
+};
+
+const finalizeScheduleValue = (
+ schedule: ScheduleBuilderValue,
+ errorMessage: string,
+): NormalizedScheduleBuilderValue => {
+ const nextValue =
+ schedule.schedule_frame === "mid"
+ ? { ...schedule, schedule_day: null }
+ : schedule;
+ if (!isNormalizedScheduleBuilderValue(nextValue)) {
+ throw new Error(errorMessage);
+ }
+ return nextValue;
+};
+
+const buildNormalizedScheduleBuilderValue = (
+ scheduleType: ScheduleBuilderType,
+ picked: ScheduleFields,
+ getDefaults: GetScheduleDefaults,
+): NormalizedScheduleBuilderValue => {
+ const { variables, constants } = SCHEDULE_SPECIFICATIONS[scheduleType];
+ const sources = [picked, constants, getDefaults(scheduleType)];
+ const schedule = SCHEDULE_FIELDS.reduce<ScheduleBuilderValue>(
+ (memo, field) => {
+ if (!(field in variables) && !(field in constants)) {
+ return { ...memo, [field]: null };
+ }
+ const value = sources.map((source) => source[field]).find(isNotNull);
+ return { ...memo, [field]: value ?? null };
+ },
+ { schedule_type: scheduleType },
+ );
+
+ return finalizeScheduleValue(
+ schedule,
+ `Could not normalize a ${scheduleType} schedule`,
+ );
+};
+
+const pickCarriedOver = (
+ previousValue: ScheduleBuilderValue,
+ nextType: ScheduleBuilderType,
+): ScheduleFields => {
+ const previousVariables =
+ SCHEDULE_SPECIFICATIONS[previousValue.schedule_type].variables;
+ const nextVariables = SCHEDULE_SPECIFICATIONS[nextType].variables;
+ const carriedFields = SCHEDULE_FIELDS.filter(
+ (field) =>
+ field in nextVariables &&
+ previousVariables[field]?.unit === nextVariables[field]?.unit,
+ );
+ return _.pick(previousValue, carriedFields);
+};
+
+export const changeScheduleType = (
+ previousValue: ScheduleBuilderValue,
+ nextType: ScheduleBuilderType,
+ getDefaults: GetScheduleDefaults,
+): NormalizedScheduleBuilderValue =>
+ buildNormalizedScheduleBuilderValue(
+ nextType,
+ pickCarriedOver(previousValue, nextType),
+ getDefaults,
+ );
+
+export const normalizeScheduleValue = (
+ value: ScheduleValue,
+ getDefaults: GetScheduleDefaults,
+): NormalizedScheduleValue => {
+ if (isScheduleCronValue(value)) {
+ return value;
+ }
+ return buildNormalizedScheduleBuilderValue(
+ value.schedule_type,
+ value,
+ getDefaults,
+ );
+};
+
+export const setScheduleField = <TField extends ScheduleField>(
+ schedule: NormalizedScheduleBuilderValue,
+ field: TField,
+ value: Exclude<ScheduleFields[TField], undefined>,
+): NormalizedScheduleBuilderValue =>
+ finalizeScheduleValue(
+ {
+ ...schedule,
+ ...SCHEDULE_SPECIFICATIONS[schedule.schedule_type].constants,
+ [field]: value,
+ },
+ `${field} cannot be set on a ${schedule.schedule_type} schedule`,
+ );
+
+export const isScheduleComplete = (value: NormalizedScheduleValue): boolean => {
+ if (isScheduleCronValue(value)) {
+ return true;
+ }
+ const { variables } = SCHEDULE_SPECIFICATIONS[value.schedule_type];
+ const requiredFields = SCHEDULE_FIELDS.filter((field) => {
+ const variable = variables[field];
+ return variable && !variable.nullable;
+ });
+ return requiredFields.every((field) => isNotNull(value[field]));
+};
diff --git a/frontend/src/metabase/common/components/Schedule/domain/schedule.unit.spec.tsx b/frontend/src/metabase/common/components/Schedule/domain/schedule.unit.spec.tsx
new file mode 100644
index 00000000000..3b9a22b5496
--- /dev/null
+++ b/frontend/src/metabase/common/components/Schedule/domain/schedule.unit.spec.tsx
@@ -0,0 +1,510 @@
+import { getDefaultsWithoutHour } from "../test-utils";
+
+import {
+ changeScheduleType,
+ getScheduleDefaults,
+ isScheduleComplete,
+ normalizeScheduleValue,
+ setScheduleField,
+} from "./schedule";
+import type {
+ NormalizedScheduleBuilderValue,
+ NormalizedScheduleValue,
+ ScheduleBuilderValue,
+ ScheduleValue,
+} from "./types";
+
+describe("isScheduleComplete", () => {
+ it.each<NormalizedScheduleValue>([
+ {
+ schedule_type: "daily",
+ schedule_hour: null,
+ schedule_minute: 0,
+ schedule_day: null,
+ schedule_frame: null,
+ },
+ {
+ schedule_type: "weekly",
+ schedule_hour: null,
+ schedule_minute: 0,
+ schedule_day: "mon",
+ schedule_frame: null,
+ },
+ {
+ schedule_type: "monthly",
+ schedule_hour: null,
+ schedule_minute: 0,
+ schedule_day: null,
+ schedule_frame: "first",
+ },
+ ])(
+ "should be false when a $schedule_type schedule has no hour",
+ (schedule) => {
+ expect(isScheduleComplete(schedule)).toBe(false);
+ },
+ );
+
+ it.each<NormalizedScheduleValue>([
+ {
+ schedule_type: "daily",
+ schedule_hour: 8,
+ schedule_minute: 0,
+ schedule_day: null,
+ schedule_frame: null,
+ },
+ {
+ schedule_type: "weekly",
+ schedule_hour: 8,
+ schedule_minute: 0,
+ schedule_day: "mon",
+ schedule_frame: null,
+ },
+ {
+ schedule_type: "monthly",
+ schedule_hour: 8,
+ schedule_minute: 0,
+ schedule_day: null,
+ 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_minute: 0,
+ schedule_day: null,
+ schedule_frame: null,
+ }),
+ ).toBe(false);
+ });
+
+ it("should be false when a monthly schedule has no frame", () => {
+ expect(
+ isScheduleComplete({
+ schedule_type: "monthly",
+ schedule_hour: 8,
+ schedule_minute: 0,
+ schedule_day: null,
+ schedule_frame: null,
+ }),
+ ).toBe(false);
+ });
+
+ it("should treat midnight as a picked hour", () => {
+ expect(
+ isScheduleComplete({
+ schedule_type: "daily",
+ schedule_hour: 0,
+ schedule_minute: 0,
+ schedule_day: null,
+ schedule_frame: null,
+ }),
+ ).toBe(true);
+ });
+
+ it.each<NormalizedScheduleValue>([
+ {
+ schedule_type: "every_n_minutes",
+ schedule_minute: null,
+ schedule_hour: null,
+ schedule_day: null,
+ schedule_frame: null,
+ },
+ {
+ schedule_type: "hourly",
+ schedule_minute: null,
+ schedule_hour: null,
+ schedule_day: null,
+ schedule_frame: null,
+ },
+ ])(
+ "should be true for a $schedule_type schedule, which needs no hour",
+ (schedule) => {
+ expect(isScheduleComplete(schedule)).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.each<NormalizedScheduleBuilderValue>([
+ {
+ schedule_type: "every_n_minutes",
+ schedule_minute: 10,
+ schedule_hour: null,
+ schedule_day: null,
+ schedule_frame: null,
+ },
+ {
+ schedule_type: "hourly",
+ schedule_minute: 0,
+ schedule_hour: null,
+ schedule_day: null,
+ schedule_frame: null,
+ },
+ {
+ schedule_type: "daily",
+ schedule_hour: 8,
+ schedule_minute: 0,
+ schedule_day: null,
+ schedule_frame: null,
+ },
+ {
+ schedule_type: "weekly",
+ schedule_day: "mon",
+ schedule_hour: 8,
+ schedule_minute: 0,
+ schedule_frame: null,
+ },
+ {
+ schedule_type: "monthly",
+ schedule_frame: "first",
+ schedule_day: null,
+ schedule_hour: 8,
+ schedule_minute: 0,
+ },
+ ])(
+ "should build the default $schedule_type schedule from the domain table",
+ (expected) => {
+ expect(
+ normalizeScheduleValue(
+ { schedule_type: expected.schedule_type },
+ getScheduleDefaults,
+ ),
+ ).toEqual(expected);
+ },
+ );
+
+ it("should keep picked values", () => {
+ expect(
+ normalizeScheduleValue(
+ {
+ schedule_type: "weekly",
+ schedule_day: "fri",
+ schedule_hour: 20,
+ schedule_minute: 0,
+ },
+ getScheduleDefaults,
+ ),
+ ).toEqual({
+ schedule_type: "weekly",
+ schedule_day: "fri",
+ schedule_frame: null,
+ schedule_hour: 20,
+ schedule_minute: 0,
+ });
+ });
+
+ it("should keep a minute the type cannot show", () => {
+ expect(
+ normalizeScheduleValue(
+ {
+ schedule_type: "weekly",
+ schedule_day: "fri",
+ schedule_hour: 20,
+ schedule_minute: 15,
+ },
+ getScheduleDefaults,
+ ),
+ ).toMatchObject({ schedule_minute: 15 });
+ });
+
+ it("should drop values the type does not use", () => {
+ expect(
+ normalizeScheduleValue(
+ {
+ schedule_type: "hourly",
+ schedule_day: "mon",
+ schedule_frame: "first",
+ schedule_hour: 8,
+ },
+ getScheduleDefaults,
+ ),
+ ).toEqual({
+ schedule_type: "hourly",
+ schedule_day: null,
+ schedule_frame: null,
+ schedule_hour: null,
+ schedule_minute: 0,
+ });
+ });
+
+ it("should clear the day when the frame is mid", () => {
+ expect(
+ normalizeScheduleValue(
+ {
+ schedule_type: "monthly",
+ schedule_frame: "mid",
+ schedule_day: "mon",
+ schedule_hour: 8,
+ },
+ getScheduleDefaults,
+ ),
+ ).toMatchObject({ schedule_frame: "mid", schedule_day: null });
+ });
+
+ 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("changeScheduleType", () => {
+ 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(
+ changeScheduleType(
+ { 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 time the user already picked", () => {
+ expect(changeScheduleType(daily, "weekly", getScheduleDefaults)).toEqual({
+ schedule_type: "weekly",
+ schedule_day: "mon",
+ schedule_frame: null,
+ schedule_hour: 20,
+ schedule_minute: 0,
+ });
+ });
+
+ it("should keep the weekday the user already picked", () => {
+ expect(
+ changeScheduleType(
+ { ...daily, schedule_type: "weekly", schedule_day: "fri" },
+ "monthly",
+ getScheduleDefaults,
+ ),
+ ).toEqual({
+ schedule_type: "monthly",
+ schedule_day: "fri",
+ schedule_frame: "first",
+ schedule_hour: 20,
+ schedule_minute: 0,
+ });
+ });
+
+ it("should keep the weekday when leaving monthly", () => {
+ expect(
+ changeScheduleType(
+ {
+ schedule_type: "monthly",
+ schedule_frame: "first",
+ schedule_day: "fri",
+ schedule_hour: 20,
+ schedule_minute: 0,
+ },
+ "weekly",
+ getScheduleDefaults,
+ ),
+ ).toEqual({
+ schedule_type: "weekly",
+ schedule_day: "fri",
+ schedule_frame: null,
+ schedule_hour: 20,
+ schedule_minute: 0,
+ });
+ });
+
+ it("should fall back to the default weekday when the previous type had none picked", () => {
+ expect(
+ changeScheduleType(
+ {
+ schedule_type: "monthly",
+ schedule_frame: "mid",
+ schedule_day: null,
+ schedule_hour: 20,
+ schedule_minute: 0,
+ },
+ "weekly",
+ getScheduleDefaults,
+ ),
+ ).toMatchObject({ schedule_type: "weekly", schedule_day: "mon" });
+ });
+
+ it("should not carry a minute past the hour into a type that hides it", () => {
+ expect(
+ changeScheduleType(
+ { schedule_type: "hourly", schedule_minute: 15 },
+ "daily",
+ getScheduleDefaults,
+ ),
+ ).toMatchObject({ schedule_type: "daily", schedule_minute: 0 });
+ });
+
+ it("should not read a by-the-minute interval as a minute past the hour", () => {
+ expect(
+ changeScheduleType(
+ { schedule_type: "every_n_minutes", schedule_minute: 30 },
+ "hourly",
+ getScheduleDefaults,
+ ),
+ ).toMatchObject({ schedule_type: "hourly", schedule_minute: 0 });
+
+ expect(
+ changeScheduleType(
+ { schedule_type: "hourly", schedule_minute: 45 },
+ "every_n_minutes",
+ getScheduleDefaults,
+ ),
+ ).toMatchObject({
+ schedule_type: "every_n_minutes",
+ schedule_minute: 10,
+ });
+ });
+
+ it("should not carry a minute the previous type hid into a type that shows it", () => {
+ const dailyWithMinute = { ...daily, schedule_minute: 30 };
+
+ expect(
+ changeScheduleType(
+ dailyWithMinute,
+ "every_n_minutes",
+ getScheduleDefaults,
+ ),
+ ).toMatchObject({ schedule_type: "every_n_minutes", schedule_minute: 10 });
+
+ expect(
+ changeScheduleType(dailyWithMinute, "hourly", getScheduleDefaults),
+ ).toMatchObject({ schedule_type: "hourly", schedule_minute: 0 });
+ });
+
+ it("should reset a minute the type hides even when the type stays the same", () => {
+ expect(
+ changeScheduleType(
+ { ...daily, schedule_minute: 15 },
+ "daily",
+ getScheduleDefaults,
+ ),
+ ).toMatchObject({ schedule_type: "daily", schedule_minute: 0 });
+ });
+
+ it("should not carry a minute the previous type hid into a type that hides it too", () => {
+ expect(
+ changeScheduleType(
+ { ...daily, schedule_minute: 30 },
+ "weekly",
+ getScheduleDefaults,
+ ),
+ ).toMatchObject({ schedule_type: "weekly", schedule_minute: 0 });
+ });
+
+ it("should give no hour to a type that does not need one", () => {
+ expect(
+ changeScheduleType(daily, "hourly", getScheduleDefaults),
+ ).toMatchObject({
+ schedule_type: "hourly",
+ schedule_hour: null,
+ });
+ });
+
+ it("should leave the hour unpicked when neither the previous schedule nor the defaults supply one", () => {
+ expect(
+ changeScheduleType(
+ { schedule_type: "hourly" },
+ "weekly",
+ getDefaultsWithoutHour,
+ ),
+ ).toMatchObject({ schedule_type: "weekly", schedule_hour: null });
+ });
+
+ it("should keep the hour the user picked even when the defaults supply none", () => {
+ expect(
+ changeScheduleType(daily, "weekly", getDefaultsWithoutHour),
+ ).toMatchObject({ schedule_type: "weekly", schedule_hour: 20 });
+ });
+});
+
+describe("setScheduleField", () => {
+ const monthly: NormalizedScheduleBuilderValue = {
+ schedule_type: "monthly",
+ schedule_frame: "first",
+ schedule_day: "mon",
+ schedule_hour: 8,
+ schedule_minute: 0,
+ };
+
+ it("should set the field and keep the rest", () => {
+ expect(setScheduleField(monthly, "schedule_hour", 20)).toEqual({
+ ...monthly,
+ schedule_hour: 20,
+ });
+ });
+
+ it("should reset a minute the type cannot show", () => {
+ expect(
+ setScheduleField(
+ { ...monthly, schedule_minute: 30 },
+ "schedule_hour",
+ 20,
+ ),
+ ).toMatchObject({ schedule_hour: 20, schedule_minute: 0 });
+ });
+
+ it("should clear the day when the frame becomes mid", () => {
+ expect(setScheduleField(monthly, "schedule_frame", "mid")).toEqual({
+ ...monthly,
+ schedule_frame: "mid",
+ schedule_day: null,
+ });
+ });
+
+ it("should leave the day unpicked when the frame leaves mid", () => {
+ const mid = setScheduleField(monthly, "schedule_frame", "mid");
+ expect(setScheduleField(mid, "schedule_frame", "last")).toEqual({
+ ...monthly,
+ schedule_frame: "last",
+ schedule_day: null,
+ });
+ });
+
+ it("should not fill in a value the user cleared", () => {
+ expect(setScheduleField(monthly, "schedule_day", null)).toEqual({
+ ...monthly,
+ schedule_day: null,
+ });
+ });
+
+ it("should reject a field the type does not use", () => {
+ expect(() =>
+ setScheduleField(
+ {
+ ...monthly,
+ schedule_type: "daily",
+ schedule_frame: null,
+ schedule_day: null,
+ },
+ "schedule_day",
+ "mon",
+ ),
+ ).toThrow();
+ });
+});
diff --git a/frontend/src/metabase/common/components/Schedule/domain/types.ts b/frontend/src/metabase/common/components/Schedule/domain/types.ts
new file mode 100644
index 00000000000..1301cc2a88a
--- /dev/null
+++ b/frontend/src/metabase/common/components/Schedule/domain/types.ts
@@ -0,0 +1,93 @@
+import type {
+ ScheduleDayType,
+ ScheduleFrameType,
+ ScheduleSettings,
+ ScheduleType,
+} from "metabase-types/api";
+
+export type CronString = string;
+
+export type ScheduleValueType = ScheduleType | "every_n_minutes" | "cron";
+export type ScheduleBuilderType = Exclude<ScheduleValueType, "cron">;
+export type ScheduleFields = Omit<ScheduleSettings, "schedule_type">;
+export type ScheduleBuilderValue = ScheduleFields & {
+ schedule_type: ScheduleBuilderType;
+};
+
+export type ScheduleCronValue = {
+ schedule_type: "cron";
+ cron: CronString;
+};
+
+export type ScheduleValue = ScheduleBuilderValue | ScheduleCronValue;
+
+export type ScheduleField = keyof ScheduleFields;
+
+type NormalizedEveryNMinutesSchedule = {
+ schedule_type: "every_n_minutes";
+ schedule_minute: number | null;
+ schedule_hour: null;
+ schedule_day: null;
+ schedule_frame: null;
+};
+
+type NormalizedHourlySchedule = {
+ schedule_type: "hourly";
+ schedule_minute: number | null;
+ schedule_hour: null;
+ schedule_day: null;
+ schedule_frame: null;
+};
+
+type NormalizedDailySchedule = {
+ schedule_type: "daily";
+ schedule_hour: number | null;
+ schedule_minute: number;
+ schedule_day: null;
+ schedule_frame: null;
+};
+
+type NormalizedWeeklySchedule = {
+ schedule_type: "weekly";
+ schedule_day: ScheduleDayType | null;
+ schedule_hour: number | null;
+ schedule_minute: number;
+ schedule_frame: null;
+};
+
+type NormalizedMonthlySchedule = {
+ schedule_type: "monthly";
+ schedule_frame: ScheduleFrameType | null;
+ schedule_day: ScheduleDayType | null;
+ schedule_hour: number | null;
+ schedule_minute: number;
+};
+
+export type NormalizedScheduleBuilderValue =
+ | NormalizedEveryNMinutesSchedule
+ | NormalizedHourlySchedule
+ | NormalizedDailySchedule
+ | NormalizedWeeklySchedule
+ | NormalizedMonthlySchedule;
+
+export type NormalizedScheduleValue =
+ | NormalizedScheduleBuilderValue
+ | ScheduleCronValue;
+
+export type ScheduleDefaults = Partial<ScheduleFields>;
+
+export type GetScheduleDefaults = (
+ scheduleType: ScheduleBuilderType,
+) => ScheduleDefaults;
+
+type ScheduleUnit = "interval" | "minute" | "hour" | "weekday" | "frame";
+
+type ScheduleVariable = { unit: ScheduleUnit; nullable?: true };
+
+export type ScheduleSpecification = {
+ variables: Partial<Record<ScheduleField, ScheduleVariable>>;
+ constants: {
+ [TField in ScheduleField]?: NonNullable<ScheduleFields[TField]>;
+ };
+ defaults: ScheduleDefaults;
+};
diff --git a/frontend/src/metabase/common/components/Schedule/test-utils.tsx b/frontend/src/metabase/common/components/Schedule/test-utils.tsx
index 74caa1a1182..91ecda61379 100644
--- a/frontend/src/metabase/common/components/Schedule/test-utils.tsx
+++ b/frontend/src/metabase/common/components/Schedule/test-utils.tsx
@@ -14,17 +14,14 @@ import {
import type { ScheduleProps } from "./Schedule";
import { Schedule } from "./Schedule";
import type {
- ScheduleBuilderType,
- ScheduleChangeEvent,
+ GetScheduleDefaults,
ScheduleValue,
ScheduleValueType,
-} from "./types";
-import type { ScheduleDefaults } from "./utils";
-import { getScheduleDefaults } from "./utils";
+} from "./domain";
+import { getScheduleDefaults } from "./domain";
+import type { ScheduleChangeEvent } from "./types";
-export const getDefaultsWithoutHour = (
- scheduleType: ScheduleBuilderType,
-): ScheduleDefaults => ({
+export const getDefaultsWithoutHour: GetScheduleDefaults = (scheduleType) => ({
...getScheduleDefaults(scheduleType),
schedule_hour: null,
});
diff --git a/frontend/src/metabase/common/components/Schedule/types.ts b/frontend/src/metabase/common/components/Schedule/types.ts
index c2cd75176cd..17a332cc66f 100644
--- a/frontend/src/metabase/common/components/Schedule/types.ts
+++ b/frontend/src/metabase/common/components/Schedule/types.ts
@@ -1,39 +1,25 @@
-import type { ScheduleSettings, ScheduleType } from "metabase-types/api";
+import type { ScheduleSettings } from "metabase-types/api";
import type { AM, PM } from "./constants";
+import type {
+ CronString,
+ NormalizedScheduleValue,
+ ScheduleField,
+} from "./domain";
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;
+ value: NormalizedScheduleValue;
/** 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],
+export type UpdateSchedule = <TField extends ScheduleField>(
+ field: TField,
+ value: Exclude<ScheduleSettings[TField], undefined>,
) => void;
diff --git a/frontend/src/metabase/common/components/Schedule/utils.tsx b/frontend/src/metabase/common/components/Schedule/utils.tsx
index 796d34637ff..89220d4bd74 100644
--- a/frontend/src/metabase/common/components/Schedule/utils.tsx
+++ b/frontend/src/metabase/common/components/Schedule/utils.tsx
@@ -1,20 +1,9 @@
import type { ReactNode } from "react";
-import { match } from "ts-pattern";
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) => {
@@ -73,176 +62,3 @@ export const measureTextWidthSafely = _.memoize(
return JSON.stringify(args);
},
);
-
-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("hourly", () => ({
- defaults: {
- schedule_day: null,
- schedule_frame: null,
- schedule_hour: null,
- schedule_minute: 0,
- },
- cron: { schedule_minute: "wildcard" },
- }))
- .with("daily", () => ({
- defaults: {
- schedule_day: null,
- schedule_frame: null,
- schedule_hour: defaultHour,
- schedule_minute: 0,
- },
- cron: { schedule_hour: "required", schedule_minute: "wildcard" },
- }))
- .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("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",
- },
- }))
- .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 50fae9228ff..283e29a7068 100644
--- a/frontend/src/metabase/common/components/Schedule/utils.unit.spec.tsx
+++ b/frontend/src/metabase/common/components/Schedule/utils.unit.spec.tsx
@@ -1,15 +1,6 @@
import type { SelectProps } from "metabase/ui";
-import { getDefaultsWithoutHour } from "./test-utils";
-import type { ScheduleBuilderValue, ScheduleValue } from "./types";
-import {
- combineConsecutiveStrings,
- getLongestSelectLabel,
- getScheduleDefaults,
- isScheduleComplete,
- normalizeScheduleValue,
- resetScheduleToTypeDefaults,
-} from "./utils";
+import { combineConsecutiveStrings, getLongestSelectLabel } from "./utils";
describe("Schedule utility functions", () => {
describe("getLongestSelectLabel", () => {
@@ -93,163 +84,3 @@ 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/dashboard/components/DashboardSubscriptionsSidebar/AddEditSidebar/AddEditEmailSidebar.tsx b/frontend/src/metabase/dashboard/components/DashboardSubscriptionsSidebar/AddEditSidebar/AddEditEmailSidebar.tsx
index 8b5bcd01fdb..c41019e9224 100644
--- a/frontend/src/metabase/dashboard/components/DashboardSubscriptionsSidebar/AddEditSidebar/AddEditEmailSidebar.tsx
+++ b/frontend/src/metabase/dashboard/components/DashboardSubscriptionsSidebar/AddEditSidebar/AddEditEmailSidebar.tsx
@@ -4,20 +4,18 @@ import { t } from "ttag";
import _ from "underscore";
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 type { ScheduleValue } from "metabase/common/components/Schedule/domain";
+import type { ScheduleChangeProp } from "metabase/common/components/Schedule/types";
import { SendTestPulse } from "metabase/common/components/SendTestPulse";
import { Sidebar } from "metabase/common/components/Sidebar";
import CS from "metabase/css/core/index.css";
import { canAccessSettings, getUser } from "metabase/current-user";
import { isEmbeddingSdk } from "metabase/embedding-sdk/config";
import { RecipientPicker } from "metabase/notifications/channels/RecipientPicker";
+import {
+ getScheduleDefaultsWithoutHour,
+ toScheduleSettings,
+} from "metabase/notifications/utils";
import { PLUGIN_DASHBOARD_SUBSCRIPTION_PARAMETERS_SECTION_OVERRIDE } from "metabase/plugins";
import { channelTargetIsValid, dashboardPulseIsValid } from "metabase/pulse";
import { useSelector } from "metabase/redux";
diff --git a/frontend/src/metabase/dashboard/components/DashboardSubscriptionsSidebar/AddEditSidebar/AddEditSlackSidebar.tsx b/frontend/src/metabase/dashboard/components/DashboardSubscriptionsSidebar/AddEditSidebar/AddEditSlackSidebar.tsx
index f6229682c08..d5daa964f5a 100644
--- a/frontend/src/metabase/dashboard/components/DashboardSubscriptionsSidebar/AddEditSidebar/AddEditSlackSidebar.tsx
+++ b/frontend/src/metabase/dashboard/components/DashboardSubscriptionsSidebar/AddEditSidebar/AddEditSlackSidebar.tsx
@@ -3,18 +3,16 @@ import { t } from "ttag";
import _ from "underscore";
import { Schedule } from "metabase/common/components/Schedule/Schedule";
-import type {
- ScheduleChangeProp,
- ScheduleValue,
-} from "metabase/common/components/Schedule/types";
-import {
- getScheduleDefaultsWithoutHour,
- toScheduleSettings,
-} from "metabase/common/components/Schedule/utils";
+import type { ScheduleValue } from "metabase/common/components/Schedule/domain";
+import type { ScheduleChangeProp } from "metabase/common/components/Schedule/types";
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 {
+ getScheduleDefaultsWithoutHour,
+ toScheduleSettings,
+} from "metabase/notifications/utils";
import { PLUGIN_DASHBOARD_SUBSCRIPTION_PARAMETERS_SECTION_OVERRIDE } from "metabase/plugins";
import { channelTargetIsValid, dashboardPulseIsValid } from "metabase/pulse";
import { useSelector } from "metabase/redux";
diff --git a/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/CreateOrEditQuestionAlertModal.tsx b/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/CreateOrEditQuestionAlertModal.tsx
index 6991f3a251d..52a8ef1671c 100644
--- a/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/CreateOrEditQuestionAlertModal.tsx
+++ b/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/CreateOrEditQuestionAlertModal.tsx
@@ -10,7 +10,7 @@ import {
useSendUnsavedNotificationMutation,
useUpdateNotificationMutation,
} from "metabase/api";
-import type { ScheduleValueType } from "metabase/common/components/Schedule/types";
+import type { ScheduleValueType } from "metabase/common/components/Schedule/domain";
import CS from "metabase/css/core/index.css";
import {
canAccessSettings,
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 8a4955062e8..369b548400d 100644
--- a/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/CreateOrEditQuestionAlertModal.unit.spec.tsx
+++ b/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/CreateOrEditQuestionAlertModal.unit.spec.tsx
@@ -537,10 +537,8 @@ describe("CreateOrEditQuestionAlertModal", () => {
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.getByRole("option", { name: /hourly/i }));
await userEvent.click(screen.getByTestId("select-frequency"));
await userEvent.click(screen.getByRole("option", { name: /daily/i }));
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 68056f5b581..9850eef26fe 100644
--- a/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/components/NotificationSchedule/NotificationSchedule.tsx
+++ b/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/components/NotificationSchedule/NotificationSchedule.tsx
@@ -10,15 +10,15 @@ import {
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";
+} from "metabase/common/components/Schedule/domain";
+import { isScheduleCronValue } from "metabase/common/components/Schedule/domain";
+import type { ScheduleChangeEvent } from "metabase/common/components/Schedule/types";
import {
DEFAULT_ALERT_SCHEDULE,
formatNotificationScheduleDescription,
+ getScheduleDefaultsWithoutHour,
} from "metabase/notifications/utils";
import { useSelector } from "metabase/redux";
import { getApplicationName } from "metabase/selectors/whitelabel";
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 6cce9951334..8f0bab73d04 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,6 +1,6 @@
import { mockSettings } from "__support__/settings";
import { renderWithProviders } from "__support__/ui";
-import type { ScheduleValueType } from "metabase/common/components/Schedule/types";
+import type { ScheduleValueType } from "metabase/common/components/Schedule/domain";
import { createMockState } from "metabase/redux/store/mocks";
import type { NotificationCronSubscription } from "metabase-types/api";
diff --git a/frontend/src/metabase/notifications/utils.ts b/frontend/src/metabase/notifications/utils.ts
index 3ecb17853d8..03483048987 100644
--- a/frontend/src/metabase/notifications/utils.ts
+++ b/frontend/src/metabase/notifications/utils.ts
@@ -3,11 +3,14 @@ import _ from "underscore";
import { cronToBuilderValue } from "metabase/common/components/Schedule/cron";
import type {
+ GetScheduleDefaults,
ScheduleBuilderValue,
ScheduleValue,
-} from "metabase/common/components/Schedule/types";
-import { isScheduleCronValue } from "metabase/common/components/Schedule/types";
-import { getScheduleDefaultsWithoutHour } from "metabase/common/components/Schedule/utils";
+} from "metabase/common/components/Schedule/domain";
+import {
+ getScheduleDefaults,
+ isScheduleCronValue,
+} from "metabase/common/components/Schedule/domain";
import type { NotificationListItem } from "metabase/notifications/types";
import { getScheduleExplanation } from "metabase/utils/cron";
import { getEmailDomain, isEmail } from "metabase/utils/email";
@@ -34,6 +37,7 @@ import type {
NotificationHandlerSlack,
NotificationRecipient,
NotificationRecipientRawValue,
+ ScheduleSettings,
UpdateAlertNotificationRequest,
User,
UserId,
@@ -42,11 +46,24 @@ import type {
import type { NotificationTriggerOption } from "./modals/CreateOrEditQuestionAlertModal/types";
+export const getScheduleDefaultsWithoutHour: GetScheduleDefaults = (
+ scheduleType,
+) => ({ ...getScheduleDefaults(scheduleType), schedule_hour: null });
+
export const DEFAULT_ALERT_SCHEDULE: ScheduleBuilderValue = {
schedule_type: "daily",
...getScheduleDefaultsWithoutHour("daily"),
};
+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 };
+};
+
const getDefaultChannelConfig = ({
channelSpec,
hookChannels,
diff --git a/frontend/src/metabase/pulse/pulse.ts b/frontend/src/metabase/pulse/pulse.ts
index 961f7260cdf..473de61c37b 100644
--- a/frontend/src/metabase/pulse/pulse.ts
+++ b/frontend/src/metabase/pulse/pulse.ts
@@ -180,7 +180,6 @@ export function createChannel(
recipients: [],
schedule_type: channelSpec.schedules[0],
schedule_day: "mon",
- schedule_hour: 8,
schedule_frame: "first",
...opts,
};
diff --git a/frontend/src/metabase/transforms/components/JobEditor/ScheduleSection/ScheduleSection.tsx b/frontend/src/metabase/transforms/components/JobEditor/ScheduleSection/ScheduleSection.tsx
index a328fdb598b..3bd7bc51b80 100644
--- a/frontend/src/metabase/transforms/components/JobEditor/ScheduleSection/ScheduleSection.tsx
+++ b/frontend/src/metabase/transforms/components/JobEditor/ScheduleSection/ScheduleSection.tsx
@@ -12,11 +12,11 @@ import {
} 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";
+} from "metabase/common/components/Schedule/domain";
+import { isScheduleCronValue } from "metabase/common/components/Schedule/domain";
+import type { ScheduleChangeEvent } from "metabase/common/components/Schedule/types";
import { TitleSection } from "metabase/common/data-studio/components/TitleSection";
import { useMetadataToasts } from "metabase/common/hooks";
import { useSetting } from "metabase/settings";