From 4fc4ba3ca9088acf74da5dffe08e8e2597b9deec Mon Sep 17 00:00:00 2001 From: Lifei Zhou Date: Thu, 7 May 2026 18:23:29 +1000 Subject: [PATCH 1/3] added quarterly option for scheduler --- .../src/components/schedule/CronPicker.tsx | 97 ++++++++++++++++++- .../schedule/__tests__/CronPicker.test.tsx | 38 ++++++++ ui/desktop/src/i18n/messages/en.json | 6 ++ 3 files changed, 137 insertions(+), 4 deletions(-) create mode 100644 ui/desktop/src/components/schedule/__tests__/CronPicker.test.tsx diff --git a/ui/desktop/src/components/schedule/CronPicker.tsx b/ui/desktop/src/components/schedule/CronPicker.tsx index 8e9cf40696df..bf800da75aa7 100644 --- a/ui/desktop/src/components/schedule/CronPicker.tsx +++ b/ui/desktop/src/components/schedule/CronPicker.tsx @@ -11,8 +11,10 @@ const i18n = defineMessages({ day: { id: 'cronPicker.day', defaultMessage: 'Day' }, week: { id: 'cronPicker.week', defaultMessage: 'Week' }, month: { id: 'cronPicker.month', defaultMessage: 'Month' }, + quarter: { id: 'cronPicker.quarter', defaultMessage: 'Quarter' }, year: { id: 'cronPicker.year', defaultMessage: 'Year' }, inMonth: { id: 'cronPicker.inMonth', defaultMessage: 'in' }, + startingMonth: { id: 'cronPicker.startingMonth', defaultMessage: 'starting month' }, january: { id: 'cronPicker.january', defaultMessage: 'January' }, february: { id: 'cronPicker.february', defaultMessage: 'February' }, march: { id: 'cronPicker.march', defaultMessage: 'March' }, @@ -39,7 +41,26 @@ const i18n = defineMessages({ atSecond: { id: 'cronPicker.atSecond', defaultMessage: 'at second' }, }); -type Period = 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year'; +type Period = 'minute' | 'hour' | 'day' | 'week' | 'month' | 'quarter' | 'year'; + +const quarterMonthsByStartMonth: Record = { + '1': '1,4,7,10', + '2': '2,5,8,11', + '3': '3,6,9,12', +}; + +const quarterDayLimitByStartMonth: Record = { + '1': 30, + '2': 28, + '3': 30, +}; + +const getQuarterStartMonth = (month: string): string | null => { + const entry = Object.entries(quarterMonthsByStartMonth).find( + ([, quarterMonths]) => quarterMonths === month + ); + return entry?.[0] ?? null; +}; type ParsedCron = { period: Period; @@ -76,6 +97,12 @@ const parseCron = (cron: string): ParsedCron => { const [second, minute, hour, dayOfMonth, month, dayOfWeek] = parts; + if (dayOfMonth !== '*') { + const quarterStartMonth = getQuarterStartMonth(month); + if (quarterStartMonth) { + return { period: 'quarter', second, minute, hour, dayOfMonth, month, dayOfWeek }; + } + } if (month !== '*' && dayOfMonth !== '*') { return { period: 'year', second, minute, hour, dayOfMonth, month, dayOfWeek }; } @@ -124,6 +151,7 @@ export const CronPicker: React.FC = ({ schedule, onChange, isVa const [dayOfWeek, setDayOfWeek] = useState('1'); const [dayOfMonth, setDayOfMonth] = useState('1'); const [month, setMonth] = useState('1'); + const [quarterStartMonth, setQuarterStartMonth] = useState('1'); const [readableCron, setReadableCron] = useState(''); useEffect(() => { @@ -138,10 +166,24 @@ export const CronPicker: React.FC = ({ schedule, onChange, isVa setDayOfWeek(parsed.dayOfWeek === '*' ? '1' : parsed.dayOfWeek); setDayOfMonth(parsed.dayOfMonth === '*' ? '1' : parsed.dayOfMonth); setMonth(parsed.month === '*' ? '1' : parsed.month); + setQuarterStartMonth(getQuarterStartMonth(parsed.month) ?? '1'); }, [schedule]); + const maxDayOfMonth = period === 'quarter' ? quarterDayLimitByStartMonth[quarterStartMonth] : 31; + + useEffect(() => { + const parsedDay = parseInt(dayOfMonth, 10); + if (!Number.isNaN(parsedDay) && parsedDay > maxDayOfMonth) { + setDayOfMonth(maxDayOfMonth.toString()); + } + }, [dayOfMonth, maxDayOfMonth]); + useEffect(() => { const hour24 = to24Hour(hour12, isPM); + const clampedDayOfMonth = Math.min( + Math.max(parseInt(dayOfMonth, 10) || 1, 1), + maxDayOfMonth + ).toString(); let cron: string; switch (period) { @@ -160,6 +202,9 @@ export const CronPicker: React.FC = ({ schedule, onChange, isVa case 'month': cron = `${second} ${minute} ${hour24} ${dayOfMonth} * *`; break; + case 'quarter': + cron = `${second} ${minute} ${hour24} ${clampedDayOfMonth} ${quarterMonthsByStartMonth[quarterStartMonth]} *`; + break; case 'year': cron = `${second} ${minute} ${hour24} ${dayOfMonth} ${month} *`; break; @@ -178,7 +223,18 @@ export const CronPicker: React.FC = ({ schedule, onChange, isVa } } // eslint-disable-next-line react-hooks/exhaustive-deps - }, [period, second, minute, hour12, isPM, dayOfWeek, dayOfMonth, month]); + }, [ + period, + second, + minute, + hour12, + isPM, + dayOfWeek, + dayOfMonth, + month, + quarterStartMonth, + maxDayOfMonth, + ]); const selectClassName = 'px-2 py-1 border rounded bg-white dark:bg-gray-800 dark:border-gray-600'; @@ -196,11 +252,40 @@ export const CronPicker: React.FC = ({ schedule, onChange, isVa +
+ {period === 'quarter' && ( +
+
+ {intl.formatMessage(i18n.startingMonth)} + +
+
+ {intl.formatMessage(i18n.onDay)} + setDayOfMonth(e.target.value)} + className="w-16 px-2 py-1 border rounded" + /> +
+
+ )} + {period === 'year' && (
{intl.formatMessage(i18n.inMonth)} @@ -231,7 +316,7 @@ export const CronPicker: React.FC = ({ schedule, onChange, isVa setDayOfMonth(e.target.value)} className="w-16 px-2 py-1 border rounded" @@ -258,7 +343,11 @@ export const CronPicker: React.FC = ({ schedule, onChange, isVa
)} - {(period === 'day' || period === 'week' || period === 'month' || period === 'year') && ( + {(period === 'day' || + period === 'week' || + period === 'month' || + period === 'quarter' || + period === 'year') && (
{intl.formatMessage(i18n.at)} + render(ui, { wrapper: IntlTestWrapper, ...options }); + +const getLastCron = (onChange: ReturnType) => { + const calls = onChange.mock.calls; + return calls[calls.length - 1]?.[0]; +}; + +describe('CronPicker', () => { + it('generates quarterly cron expressions from the quarter preset', async () => { + const user = userEvent.setup(); + const onChange = vi.fn(); + + renderWithIntl(); + + await user.selectOptions(screen.getAllByRole('combobox')[0], 'quarter'); + + await waitFor(() => { + expect(getLastCron(onChange)).toBe('0 0 14 1 1,4,7,10 *'); + }); + + const dayInput = screen.getAllByRole('spinbutton')[0]; + await user.clear(dayInput); + await user.type(dayInput, '31'); + await user.selectOptions(screen.getAllByRole('combobox')[1], '2'); + + await waitFor(() => { + expect(dayInput).toHaveValue(28); + expect(getLastCron(onChange)).toBe('0 0 14 28 2,5,8,11 *'); + }); + }); +}); diff --git a/ui/desktop/src/i18n/messages/en.json b/ui/desktop/src/i18n/messages/en.json index bc4378d86869..a2bc2a12df16 100644 --- a/ui/desktop/src/i18n/messages/en.json +++ b/ui/desktop/src/i18n/messages/en.json @@ -575,12 +575,18 @@ "cronPicker.onDay": { "defaultMessage": "on day" }, + "cronPicker.quarter": { + "defaultMessage": "Quarter" + }, "cronPicker.saturday": { "defaultMessage": "Saturday" }, "cronPicker.september": { "defaultMessage": "September" }, + "cronPicker.startingMonth": { + "defaultMessage": "starting month" + }, "cronPicker.sunday": { "defaultMessage": "Sunday" }, From a7c83cd9173e2ccf5b6395c8a934d669f4b151b4 Mon Sep 17 00:00:00 2001 From: Lifei Zhou Date: Thu, 7 May 2026 20:09:22 +1000 Subject: [PATCH 2/3] added custom cron expression --- .../src/components/schedule/CronPicker.tsx | 188 ++++++++++++++---- .../schedule/__tests__/CronPicker.test.tsx | 94 +++++++++ ui/desktop/src/i18n/messages/en.json | 15 ++ 3 files changed, 263 insertions(+), 34 deletions(-) diff --git a/ui/desktop/src/components/schedule/CronPicker.tsx b/ui/desktop/src/components/schedule/CronPicker.tsx index bf800da75aa7..13f5cba240de 100644 --- a/ui/desktop/src/components/schedule/CronPicker.tsx +++ b/ui/desktop/src/components/schedule/CronPicker.tsx @@ -6,6 +6,7 @@ import { defineMessages, useIntl } from '../../i18n'; const i18n = defineMessages({ every: { id: 'cronPicker.every', defaultMessage: 'Every' }, + mode: { id: 'cronPicker.mode', defaultMessage: 'Mode' }, minute: { id: 'cronPicker.minute', defaultMessage: 'Minute' }, hour: { id: 'cronPicker.hour', defaultMessage: 'Hour' }, day: { id: 'cronPicker.day', defaultMessage: 'Day' }, @@ -13,6 +14,16 @@ const i18n = defineMessages({ month: { id: 'cronPicker.month', defaultMessage: 'Month' }, quarter: { id: 'cronPicker.quarter', defaultMessage: 'Quarter' }, year: { id: 'cronPicker.year', defaultMessage: 'Year' }, + custom: { id: 'cronPicker.custom', defaultMessage: 'Custom cron' }, + cronExpression: { id: 'cronPicker.cronExpression', defaultMessage: 'Cron expression' }, + emptyCronError: { + id: 'cronPicker.emptyCronError', + defaultMessage: 'Cron expression cannot be empty', + }, + invalidDayOfMonth: { + id: 'cronPicker.invalidDayOfMonth', + defaultMessage: 'Day must be between 1 and {max}', + }, inMonth: { id: 'cronPicker.inMonth', defaultMessage: 'in' }, startingMonth: { id: 'cronPicker.startingMonth', defaultMessage: 'starting month' }, january: { id: 'cronPicker.january', defaultMessage: 'January' }, @@ -41,7 +52,7 @@ const i18n = defineMessages({ atSecond: { id: 'cronPicker.atSecond', defaultMessage: 'at second' }, }); -type Period = 'minute' | 'hour' | 'day' | 'week' | 'month' | 'quarter' | 'year'; +type Period = 'minute' | 'hour' | 'day' | 'week' | 'month' | 'quarter' | 'year' | 'custom'; const quarterMonthsByStartMonth: Record = { '1': '1,4,7,10', @@ -72,6 +83,53 @@ type ParsedCron = { dayOfWeek: string; }; +const defaultParsedCron: ParsedCron = { + period: 'day', + second: '0', + minute: '0', + hour: '14', + dayOfMonth: '*', + month: '*', + dayOfWeek: '*', +}; + +const normalizeCronParts = (cron: string): string[] | null => { + const parts = cron.trim().split(/\s+/); + if (parts.length === 5) { + return ['0', ...parts]; + } + if (parts.length === 6) { + return parts; + } + return null; +}; + +const isSingleNumericValue = (value: string): boolean => /^\d+$/.test(value); + +const getValidDayOfMonth = (value: string, max: number): string | null => { + if (!isSingleNumericValue(value)) { + return null; + } + const parsedDay = parseInt(value, 10); + if (parsedDay < 1 || parsedDay > max) { + return null; + } + return parsedDay.toString(); +}; + +const asCustomCron = (parts: string[]): ParsedCron => { + const [second, minute, hour, dayOfMonth, month, dayOfWeek] = parts; + return { period: 'custom', second, minute, hour, dayOfMonth, month, dayOfWeek }; +}; + +const describeCron = (cron: string): string => { + const parts = cron.trim().split(/\s+/); + if (parts.length === 5 || parts.length === 6) { + return cronstrue.toString(parts.join(' ')); + } + throw new Error('Expected 5 or 6 fields'); +}; + interface CronPickerProps { schedule: ScheduledJob | null; onChange: (cron: string) => void; @@ -79,43 +137,60 @@ interface CronPickerProps { } const parseCron = (cron: string): ParsedCron => { - const parts = cron.split(' '); - if (parts.length === 5) { - parts.unshift('0'); + if (!cron.trim()) { + return defaultParsedCron; } - if (parts.length !== 6) { - return { - period: 'day', - second: '0', - minute: '0', - hour: '14', - dayOfMonth: '*', - month: '*', - dayOfWeek: '*', - }; + + const parts = normalizeCronParts(cron); + if (!parts) { + return { ...defaultParsedCron, period: 'custom' }; } const [second, minute, hour, dayOfMonth, month, dayOfWeek] = parts; + if (!isSingleNumericValue(second)) { + return asCustomCron(parts); + } + if (dayOfMonth !== '*') { const quarterStartMonth = getQuarterStartMonth(month); - if (quarterStartMonth) { + const dayOfMonthNumber = parseInt(dayOfMonth, 10); + if ( + quarterStartMonth && + isSingleNumericValue(dayOfMonth) && + dayOfMonthNumber <= quarterDayLimitByStartMonth[quarterStartMonth] + ) { return { period: 'quarter', second, minute, hour, dayOfMonth, month, dayOfWeek }; } } if (month !== '*' && dayOfMonth !== '*') { + if (!isSingleNumericValue(month) || !isSingleNumericValue(dayOfMonth)) { + return asCustomCron(parts); + } return { period: 'year', second, minute, hour, dayOfMonth, month, dayOfWeek }; } if (dayOfMonth !== '*') { + if (!isSingleNumericValue(dayOfMonth)) { + return asCustomCron(parts); + } return { period: 'month', second, minute, hour, dayOfMonth, month, dayOfWeek }; } if (dayOfWeek !== '*') { + if (!isSingleNumericValue(dayOfWeek)) { + return asCustomCron(parts); + } return { period: 'week', second, minute, hour, dayOfMonth, month, dayOfWeek }; } if (hour !== '*') { + if (!isSingleNumericValue(hour)) { + return asCustomCron(parts); + } return { period: 'day', second, minute, hour, dayOfMonth, month, dayOfWeek }; } if (minute !== '*') { + if (!isSingleNumericValue(minute)) { + return asCustomCron(parts); + } return { period: 'hour', second, minute, hour, dayOfMonth, month, dayOfWeek }; } return { period: 'minute', second, minute, hour, dayOfMonth, month, dayOfWeek }; @@ -152,10 +227,13 @@ export const CronPicker: React.FC = ({ schedule, onChange, isVa const [dayOfMonth, setDayOfMonth] = useState('1'); const [month, setMonth] = useState('1'); const [quarterStartMonth, setQuarterStartMonth] = useState('1'); + const [customCron, setCustomCron] = useState('0 0 14 * * *'); const [readableCron, setReadableCron] = useState(''); + const [hasCronError, setHasCronError] = useState(false); useEffect(() => { - const parsed = parseCron(schedule?.cron || ''); + const sourceCron = schedule?.cron || ''; + const parsed = parseCron(sourceCron); setPeriod(parsed.period); setSecond(parsed.second === '*' ? '0' : parsed.second); setMinute(parsed.minute === '*' ? '0' : parsed.minute); @@ -167,6 +245,7 @@ export const CronPicker: React.FC = ({ schedule, onChange, isVa setDayOfMonth(parsed.dayOfMonth === '*' ? '1' : parsed.dayOfMonth); setMonth(parsed.month === '*' ? '1' : parsed.month); setQuarterStartMonth(getQuarterStartMonth(parsed.month) ?? '1'); + setCustomCron(sourceCron || '0 0 14 * * *'); }, [schedule]); const maxDayOfMonth = period === 'quarter' ? quarterDayLimitByStartMonth[quarterStartMonth] : 31; @@ -180,13 +259,28 @@ export const CronPicker: React.FC = ({ schedule, onChange, isVa useEffect(() => { const hour24 = to24Hour(hour12, isPM); - const clampedDayOfMonth = Math.min( - Math.max(parseInt(dayOfMonth, 10) || 1, 1), - maxDayOfMonth - ).toString(); + const validDayOfMonth = getValidDayOfMonth(dayOfMonth, maxDayOfMonth); let cron: string; + if ( + (period === 'month' || period === 'quarter' || period === 'year') && + validDayOfMonth === null + ) { + const invalidDayCron = + period === 'quarter' + ? `${second} ${minute} ${hour24} 0 ${quarterMonthsByStartMonth[quarterStartMonth]} *` + : `${second} ${minute} ${hour24} 0 ${period === 'year' ? month : '*'} *`; + onChange(invalidDayCron); + isValid(false); + setHasCronError(true); + setReadableCron(intl.formatMessage(i18n.invalidDayOfMonth, { max: maxDayOfMonth })); + return; + } + switch (period) { + case 'custom': + cron = customCron; + break; case 'minute': cron = `${second} * * * * *`; break; @@ -200,27 +294,32 @@ export const CronPicker: React.FC = ({ schedule, onChange, isVa cron = `${second} ${minute} ${hour24} * * ${dayOfWeek}`; break; case 'month': - cron = `${second} ${minute} ${hour24} ${dayOfMonth} * *`; + cron = `${second} ${minute} ${hour24} ${validDayOfMonth} * *`; break; case 'quarter': - cron = `${second} ${minute} ${hour24} ${clampedDayOfMonth} ${quarterMonthsByStartMonth[quarterStartMonth]} *`; + cron = `${second} ${minute} ${hour24} ${validDayOfMonth} ${quarterMonthsByStartMonth[quarterStartMonth]} *`; break; case 'year': - cron = `${second} ${minute} ${hour24} ${dayOfMonth} ${month} *`; + cron = `${second} ${minute} ${hour24} ${validDayOfMonth} ${month} *`; break; default: cron = '0 0 0 * * *'; } onChange(cron); - if (cron) { - const cronWithoutSeconds = cron.split(' ').slice(1).join(' '); - try { - setReadableCron(cronstrue.toString(cronWithoutSeconds)); - isValid(true); - } catch (e) { - isValid(false); - setReadableCron('error: ' + errorMessage(e)); - } + if (!cron.trim()) { + isValid(false); + setHasCronError(true); + setReadableCron(intl.formatMessage(i18n.emptyCronError)); + return; + } + try { + setReadableCron(describeCron(cron)); + setHasCronError(false); + isValid(true); + } catch (e) { + isValid(false); + setHasCronError(true); + setReadableCron(errorMessage(e).replace(/^Error:\s*/, '')); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [ @@ -234,6 +333,7 @@ export const CronPicker: React.FC = ({ schedule, onChange, isVa month, quarterStartMonth, maxDayOfMonth, + customCron, ]); const selectClassName = 'px-2 py-1 border rounded bg-white dark:bg-gray-800 dark:border-gray-600'; @@ -241,7 +341,9 @@ export const CronPicker: React.FC = ({ schedule, onChange, isVa return (
- {intl.formatMessage(i18n.every)} + + {intl.formatMessage(period === 'custom' ? i18n.mode : i18n.every)} +
+ {period === 'custom' && ( +
+ + setCustomCron(e.target.value)} + className="w-full px-2 py-1 border rounded" + /> +
+ )} + {period === 'quarter' && (
@@ -407,7 +525,9 @@ export const CronPicker: React.FC = ({ schedule, onChange, isVa )}
-
{readableCron}
+
+ {readableCron} +
); }; diff --git a/ui/desktop/src/components/schedule/__tests__/CronPicker.test.tsx b/ui/desktop/src/components/schedule/__tests__/CronPicker.test.tsx index 911114a83962..123440bdedfc 100644 --- a/ui/desktop/src/components/schedule/__tests__/CronPicker.test.tsx +++ b/ui/desktop/src/components/schedule/__tests__/CronPicker.test.tsx @@ -3,6 +3,7 @@ import userEvent from '@testing-library/user-event'; import { describe, expect, it, vi } from 'vitest'; import { IntlTestWrapper } from '../../../i18n/test-utils'; import { CronPicker } from '../CronPicker'; +import type { ScheduledJob } from '../../../schedule'; const renderWithIntl = (ui: React.ReactElement, options?: RenderOptions) => render(ui, { wrapper: IntlTestWrapper, ...options }); @@ -12,6 +13,12 @@ const getLastCron = (onChange: ReturnType) => { return calls[calls.length - 1]?.[0]; }; +const scheduledJob = (cron: string): ScheduledJob => ({ + id: 'quarterly-report', + source: 'dummy.yaml', + cron, +}); + describe('CronPicker', () => { it('generates quarterly cron expressions from the quarter preset', async () => { const user = userEvent.setup(); @@ -35,4 +42,91 @@ describe('CronPicker', () => { expect(getLastCron(onChange)).toBe('0 0 14 28 2,5,8,11 *'); }); }); + + it('marks invalid quarter day input as invalid instead of silently clamping to day one', async () => { + const user = userEvent.setup(); + const onChange = vi.fn(); + const isValid = vi.fn(); + + renderWithIntl(); + + await user.selectOptions(screen.getAllByRole('combobox')[0], 'quarter'); + const dayInput = screen.getAllByRole('spinbutton')[0]; + await user.clear(dayInput); + await user.type(dayInput, '0'); + + await waitFor(() => { + expect(dayInput).toHaveValue(0); + expect(isValid).toHaveBeenLastCalledWith(false); + expect(getLastCron(onChange)).toBe('0 0 14 0 1,4,7,10 *'); + }); + }); + + it('uses custom cron for cron expressions that presets cannot represent', async () => { + const onChange = vi.fn(); + + renderWithIntl( + + ); + + const [periodSelect] = screen.getAllByRole('combobox'); + + await waitFor(() => { + expect(periodSelect).toHaveValue('custom'); + expect(screen.getByLabelText('Cron expression')).toHaveValue('0 0 14 31 1,4,7,10 *'); + expect(getLastCron(onChange)).toBe('0 0 14 31 1,4,7,10 *'); + }); + }); + + it('uses custom cron when seconds cannot be represented by presets', async () => { + const onChange = vi.fn(); + + renderWithIntl( + + ); + + const [periodSelect] = screen.getAllByRole('combobox'); + + await waitFor(() => { + expect(periodSelect).toHaveValue('custom'); + expect(screen.getByLabelText('Cron expression')).toHaveValue('* 0 14 * * *'); + expect(getLastCron(onChange)).toBe('* 0 14 * * *'); + }); + }); + + it('generates cron from custom cron input', async () => { + const user = userEvent.setup(); + const onChange = vi.fn(); + + renderWithIntl(); + + await user.selectOptions(screen.getAllByRole('combobox')[0], 'custom'); + const customCronInput = screen.getByLabelText('Cron expression'); + await user.clear(customCronInput); + await user.type(customCronInput, '0 9 31 1,4,7,10 *'); + + await waitFor(() => { + expect(getLastCron(onChange)).toBe('0 9 31 1,4,7,10 *'); + }); + }); + + it('marks invalid custom cron input as invalid', async () => { + const user = userEvent.setup(); + const isValid = vi.fn(); + + renderWithIntl(); + + await user.selectOptions(screen.getAllByRole('combobox')[0], 'custom'); + const customCronInput = screen.getByLabelText('Cron expression'); + await user.clear(customCronInput); + await user.type(customCronInput, '99 0 14 * * *'); + + await waitFor(() => { + expect(isValid).toHaveBeenLastCalledWith(false); + }); + }); }); diff --git a/ui/desktop/src/i18n/messages/en.json b/ui/desktop/src/i18n/messages/en.json index a2bc2a12df16..9d1c1e435464 100644 --- a/ui/desktop/src/i18n/messages/en.json +++ b/ui/desktop/src/i18n/messages/en.json @@ -518,12 +518,21 @@ "cronPicker.august": { "defaultMessage": "August" }, + "cronPicker.cronExpression": { + "defaultMessage": "Cron expression" + }, + "cronPicker.custom": { + "defaultMessage": "Custom cron" + }, "cronPicker.day": { "defaultMessage": "Day" }, "cronPicker.december": { "defaultMessage": "December" }, + "cronPicker.emptyCronError": { + "defaultMessage": "Cron expression cannot be empty" + }, "cronPicker.every": { "defaultMessage": "Every" }, @@ -539,6 +548,9 @@ "cronPicker.inMonth": { "defaultMessage": "in" }, + "cronPicker.invalidDayOfMonth": { + "defaultMessage": "Day must be between 1 and {max}" + }, "cronPicker.january": { "defaultMessage": "January" }, @@ -557,6 +569,9 @@ "cronPicker.minute": { "defaultMessage": "Minute" }, + "cronPicker.mode": { + "defaultMessage": "Mode" + }, "cronPicker.monday": { "defaultMessage": "Monday" }, From 971bb143330d7e5e15ea3103aefee5e926b4906b Mon Sep 17 00:00:00 2001 From: Lifei Zhou Date: Thu, 7 May 2026 20:34:24 +1000 Subject: [PATCH 3/3] render period cron expression in custom mode --- .../src/components/schedule/CronPicker.tsx | 206 +++--------------- .../schedule/__tests__/CronPicker.test.tsx | 21 ++ ui/desktop/src/utils/cronSchedule.ts | 184 ++++++++++++++++ 3 files changed, 236 insertions(+), 175 deletions(-) create mode 100644 ui/desktop/src/utils/cronSchedule.ts diff --git a/ui/desktop/src/components/schedule/CronPicker.tsx b/ui/desktop/src/components/schedule/CronPicker.tsx index 13f5cba240de..a34985bf4f48 100644 --- a/ui/desktop/src/components/schedule/CronPicker.tsx +++ b/ui/desktop/src/components/schedule/CronPicker.tsx @@ -1,8 +1,16 @@ import React, { useState, useEffect } from 'react'; -import cronstrue from 'cronstrue'; import { ScheduledJob } from '../../schedule'; import { errorMessage } from '../../utils/conversionUtils'; import { defineMessages, useIntl } from '../../i18n'; +import { + buildCronForPeriod, + describeCron, + getQuarterStartMonth, + getValidDayOfMonth, + parseCron, + quarterDayLimitByStartMonth, + type Period, +} from '../../utils/cronSchedule'; const i18n = defineMessages({ every: { id: 'cronPicker.every', defaultMessage: 'Every' }, @@ -52,150 +60,12 @@ const i18n = defineMessages({ atSecond: { id: 'cronPicker.atSecond', defaultMessage: 'at second' }, }); -type Period = 'minute' | 'hour' | 'day' | 'week' | 'month' | 'quarter' | 'year' | 'custom'; - -const quarterMonthsByStartMonth: Record = { - '1': '1,4,7,10', - '2': '2,5,8,11', - '3': '3,6,9,12', -}; - -const quarterDayLimitByStartMonth: Record = { - '1': 30, - '2': 28, - '3': 30, -}; - -const getQuarterStartMonth = (month: string): string | null => { - const entry = Object.entries(quarterMonthsByStartMonth).find( - ([, quarterMonths]) => quarterMonths === month - ); - return entry?.[0] ?? null; -}; - -type ParsedCron = { - period: Period; - second: string; - minute: string; - hour: string; - dayOfMonth: string; - month: string; - dayOfWeek: string; -}; - -const defaultParsedCron: ParsedCron = { - period: 'day', - second: '0', - minute: '0', - hour: '14', - dayOfMonth: '*', - month: '*', - dayOfWeek: '*', -}; - -const normalizeCronParts = (cron: string): string[] | null => { - const parts = cron.trim().split(/\s+/); - if (parts.length === 5) { - return ['0', ...parts]; - } - if (parts.length === 6) { - return parts; - } - return null; -}; - -const isSingleNumericValue = (value: string): boolean => /^\d+$/.test(value); - -const getValidDayOfMonth = (value: string, max: number): string | null => { - if (!isSingleNumericValue(value)) { - return null; - } - const parsedDay = parseInt(value, 10); - if (parsedDay < 1 || parsedDay > max) { - return null; - } - return parsedDay.toString(); -}; - -const asCustomCron = (parts: string[]): ParsedCron => { - const [second, minute, hour, dayOfMonth, month, dayOfWeek] = parts; - return { period: 'custom', second, minute, hour, dayOfMonth, month, dayOfWeek }; -}; - -const describeCron = (cron: string): string => { - const parts = cron.trim().split(/\s+/); - if (parts.length === 5 || parts.length === 6) { - return cronstrue.toString(parts.join(' ')); - } - throw new Error('Expected 5 or 6 fields'); -}; - interface CronPickerProps { schedule: ScheduledJob | null; onChange: (cron: string) => void; isValid: (valid: boolean) => void; } -const parseCron = (cron: string): ParsedCron => { - if (!cron.trim()) { - return defaultParsedCron; - } - - const parts = normalizeCronParts(cron); - if (!parts) { - return { ...defaultParsedCron, period: 'custom' }; - } - - const [second, minute, hour, dayOfMonth, month, dayOfWeek] = parts; - - if (!isSingleNumericValue(second)) { - return asCustomCron(parts); - } - - if (dayOfMonth !== '*') { - const quarterStartMonth = getQuarterStartMonth(month); - const dayOfMonthNumber = parseInt(dayOfMonth, 10); - if ( - quarterStartMonth && - isSingleNumericValue(dayOfMonth) && - dayOfMonthNumber <= quarterDayLimitByStartMonth[quarterStartMonth] - ) { - return { period: 'quarter', second, minute, hour, dayOfMonth, month, dayOfWeek }; - } - } - if (month !== '*' && dayOfMonth !== '*') { - if (!isSingleNumericValue(month) || !isSingleNumericValue(dayOfMonth)) { - return asCustomCron(parts); - } - return { period: 'year', second, minute, hour, dayOfMonth, month, dayOfWeek }; - } - if (dayOfMonth !== '*') { - if (!isSingleNumericValue(dayOfMonth)) { - return asCustomCron(parts); - } - return { period: 'month', second, minute, hour, dayOfMonth, month, dayOfWeek }; - } - if (dayOfWeek !== '*') { - if (!isSingleNumericValue(dayOfWeek)) { - return asCustomCron(parts); - } - return { period: 'week', second, minute, hour, dayOfMonth, month, dayOfWeek }; - } - if (hour !== '*') { - if (!isSingleNumericValue(hour)) { - return asCustomCron(parts); - } - return { period: 'day', second, minute, hour, dayOfMonth, month, dayOfWeek }; - } - if (minute !== '*') { - if (!isSingleNumericValue(minute)) { - return asCustomCron(parts); - } - return { period: 'hour', second, minute, hour, dayOfMonth, month, dayOfWeek }; - } - return { period: 'minute', second, minute, hour, dayOfMonth, month, dayOfWeek }; -}; - const to24Hour = (hour12: number, isPM: boolean): number => { if (hour12 === 12) { return isPM ? 12 : 0; @@ -231,6 +101,19 @@ export const CronPicker: React.FC = ({ schedule, onChange, isVa const [readableCron, setReadableCron] = useState(''); const [hasCronError, setHasCronError] = useState(false); + const getCurrentCron = (selectedPeriod: Period, validDayOfMonth: string | null): string => + buildCronForPeriod({ + period: selectedPeriod, + second, + minute, + hour24: to24Hour(hour12, isPM), + dayOfWeek, + dayOfMonth: validDayOfMonth, + month, + quarterStartMonth, + customCron, + }); + useEffect(() => { const sourceCron = schedule?.cron || ''; const parsed = parseCron(sourceCron); @@ -258,53 +141,20 @@ export const CronPicker: React.FC = ({ schedule, onChange, isVa }, [dayOfMonth, maxDayOfMonth]); useEffect(() => { - const hour24 = to24Hour(hour12, isPM); const validDayOfMonth = getValidDayOfMonth(dayOfMonth, maxDayOfMonth); - let cron: string; if ( (period === 'month' || period === 'quarter' || period === 'year') && validDayOfMonth === null ) { - const invalidDayCron = - period === 'quarter' - ? `${second} ${minute} ${hour24} 0 ${quarterMonthsByStartMonth[quarterStartMonth]} *` - : `${second} ${minute} ${hour24} 0 ${period === 'year' ? month : '*'} *`; - onChange(invalidDayCron); + onChange(getCurrentCron(period, null)); isValid(false); setHasCronError(true); setReadableCron(intl.formatMessage(i18n.invalidDayOfMonth, { max: maxDayOfMonth })); return; } - switch (period) { - case 'custom': - cron = customCron; - break; - case 'minute': - cron = `${second} * * * * *`; - break; - case 'hour': - cron = `${second} ${minute} * * * *`; - break; - case 'day': - cron = `${second} ${minute} ${hour24} * * *`; - break; - case 'week': - cron = `${second} ${minute} ${hour24} * * ${dayOfWeek}`; - break; - case 'month': - cron = `${second} ${minute} ${hour24} ${validDayOfMonth} * *`; - break; - case 'quarter': - cron = `${second} ${minute} ${hour24} ${validDayOfMonth} ${quarterMonthsByStartMonth[quarterStartMonth]} *`; - break; - case 'year': - cron = `${second} ${minute} ${hour24} ${validDayOfMonth} ${month} *`; - break; - default: - cron = '0 0 0 * * *'; - } + const cron = getCurrentCron(period, validDayOfMonth); onChange(cron); if (!cron.trim()) { isValid(false); @@ -346,7 +196,13 @@ export const CronPicker: React.FC = ({ schedule, onChange, isVa