chore: 纳入本地 Dify 1.19.0 源码及品牌与免登改动
演示目录只保留可重建的源码。运行密钥、数据卷、依赖和带口令的本地配置不进入仓库。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
60158935f4
commit
6519682885
15831 files changed
+3063428
No files matched your search
+57
@@ -0,0 +1,57 @@
|
||||
import type { ScheduleTriggerNodeType } from '../types'
|
||||
import { screen } from '@testing-library/react'
|
||||
import { renderNodeComponent } from '@/app/components/workflow/__tests__/workflow-test-env'
|
||||
import { BlockEnum } from '@/app/components/workflow/types'
|
||||
import Node from '../node'
|
||||
|
||||
const createNodeData = (
|
||||
overrides: Partial<ScheduleTriggerNodeType> = {},
|
||||
): ScheduleTriggerNodeType => ({
|
||||
title: 'Schedule Trigger',
|
||||
desc: '',
|
||||
type: BlockEnum.TriggerSchedule,
|
||||
mode: 'visual',
|
||||
frequency: 'daily',
|
||||
timezone: 'UTC',
|
||||
visual_config: {
|
||||
time: '11:30 AM',
|
||||
},
|
||||
...overrides,
|
||||
})
|
||||
|
||||
describe('TriggerScheduleNode', () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers()
|
||||
vi.setSystemTime(new Date('2026-01-15T12:00:00Z'))
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
// The node should surface the computed next execution time for both valid and invalid schedules.
|
||||
describe('Rendering', () => {
|
||||
it('should render the next execution label and computed execution time', () => {
|
||||
const data = createNodeData()
|
||||
|
||||
renderNodeComponent(Node, data)
|
||||
|
||||
expect(
|
||||
screen.getByText('workflowIntegrations.nodes.triggerSchedule.nextExecutionTime'),
|
||||
).toBeInTheDocument()
|
||||
expect(screen.getByText(/January 16, 2026, 11:30\sAM/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('should render the placeholder when cron mode has an invalid expression', () => {
|
||||
renderNodeComponent(
|
||||
Node,
|
||||
createNodeData({
|
||||
mode: 'cron',
|
||||
cron_expression: 'invalid cron',
|
||||
}),
|
||||
)
|
||||
|
||||
expect(screen.getByText('--')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
})
|
||||
+174
@@ -0,0 +1,174 @@
|
||||
import type { ScheduleTriggerNodeType } from '../types'
|
||||
import { screen, within } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { BlockEnum } from '@/app/components/workflow/types'
|
||||
import { renderNodePanel } from '../../__tests__/render-node-panel'
|
||||
import Panel from '../panel'
|
||||
|
||||
// Execution previews own their scheduling service; this suite edits the persisted schedule.
|
||||
vi.mock('../components/next-execution-times', () => ({ default: () => null }))
|
||||
|
||||
const createData = (overrides: Partial<ScheduleTriggerNodeType> = {}): ScheduleTriggerNodeType => ({
|
||||
title: 'Schedule Trigger',
|
||||
desc: '',
|
||||
type: BlockEnum.TriggerSchedule,
|
||||
mode: 'visual',
|
||||
frequency: 'daily',
|
||||
timezone: 'UTC',
|
||||
visual_config: {
|
||||
time: '11:30 AM',
|
||||
weekdays: ['mon'],
|
||||
on_minute: 15,
|
||||
monthly_days: [1],
|
||||
},
|
||||
...overrides,
|
||||
})
|
||||
|
||||
const renderPanel = (data = createData(), readOnly = false) =>
|
||||
renderNodePanel(Panel, data, {
|
||||
initialStoreState: { canvasReadOnly: readOnly },
|
||||
})
|
||||
const cronButton = () =>
|
||||
screen.getByRole('button', {
|
||||
name: 'workflowIntegrations.nodes.triggerSchedule.useCronExpression',
|
||||
})
|
||||
const frequencyPicker = () => screen.getByRole('combobox', { name: /frequencyLabel/ })
|
||||
|
||||
describe('TriggerSchedulePanel', () => {
|
||||
it('lets a read-only workflow browse the time without editing it', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { data } = renderPanel(createData(), true)
|
||||
const trigger = screen.getByRole('button', { name: /11:30 AM.*UTC/ })
|
||||
expect(trigger).toHaveAttribute('data-readonly')
|
||||
await user.click(trigger)
|
||||
expect(await screen.findByRole('dialog')).toBeInTheDocument()
|
||||
const [hours] = screen.getAllByRole('listbox')
|
||||
await user.click(within(hours!).getByRole('option', { name: '2' }))
|
||||
expect(within(hours!).getByRole('option', { name: '11' })).toHaveAttribute(
|
||||
'aria-selected',
|
||||
'true',
|
||||
)
|
||||
expect(screen.queryByRole('button', { name: /operation\.ok/i })).not.toBeInTheDocument()
|
||||
await user.keyboard('{Escape}')
|
||||
expect(data()).toMatchObject(createData())
|
||||
})
|
||||
|
||||
it('saves frequency and time before switching to cron mode', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { data } = renderPanel()
|
||||
await user.click(frequencyPicker())
|
||||
await user.click(
|
||||
screen.getByRole('option', {
|
||||
name: 'workflowIntegrations.nodes.triggerSchedule.frequency.weekly',
|
||||
}),
|
||||
)
|
||||
await user.click(screen.getByText('workflow.nodes.triggerSchedule.time', { exact: true }))
|
||||
const trigger = screen.getByRole('button', { name: /11:30 AM.*UTC/ })
|
||||
expect(trigger).toHaveFocus()
|
||||
await user.keyboard('{Enter}')
|
||||
await user.click(screen.getByRole('option', { name: '2' }))
|
||||
await user.click(screen.getByText('45'))
|
||||
await user.click(screen.getByText('PM'))
|
||||
await user.click(screen.getByRole('button', { name: /operation\.ok/i }))
|
||||
expect(data()).toMatchObject({
|
||||
frequency: 'weekly',
|
||||
visual_config: { time: '2:45 PM' },
|
||||
timezone: 'UTC',
|
||||
})
|
||||
expect(screen.getByRole('button', { name: /2:45 PM.*UTC/ })).toBeInTheDocument()
|
||||
await user.click(cronButton())
|
||||
expect(data().mode).toBe('cron')
|
||||
expect(
|
||||
screen.getByRole('textbox', { name: 'workflow.nodes.triggerSchedule.cronExpression' }),
|
||||
).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('updates weekly and monthly selections while preserving other schedule settings', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { data } = renderPanel(createData({ frequency: 'weekly' }))
|
||||
await user.click(screen.getByRole('button', { name: 'Wed' }))
|
||||
expect(data().visual_config?.weekdays).toEqual(['mon', 'wed'])
|
||||
await user.click(frequencyPicker())
|
||||
await user.click(
|
||||
screen.getByRole('option', {
|
||||
name: 'workflowIntegrations.nodes.triggerSchedule.frequency.monthly',
|
||||
}),
|
||||
)
|
||||
await user.click(
|
||||
screen.getByRole('button', {
|
||||
name: 'workflowIntegrations.nodes.triggerSchedule.lastDay',
|
||||
pressed: false,
|
||||
}),
|
||||
)
|
||||
expect(data()).toMatchObject({
|
||||
frequency: 'monthly',
|
||||
timezone: 'UTC',
|
||||
visual_config: { monthly_days: [1, 'last'], time: '11:30 AM' },
|
||||
})
|
||||
})
|
||||
|
||||
it('saves an edited cron expression', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { data } = renderPanel(
|
||||
createData({ mode: 'cron', frequency: undefined, cron_expression: '0 0 * * *' }),
|
||||
)
|
||||
const input = screen.getByRole('textbox', {
|
||||
name: 'workflow.nodes.triggerSchedule.cronExpression',
|
||||
})
|
||||
await user.clear(input)
|
||||
await user.type(input, '*/5 * * * *')
|
||||
expect(data().cron_expression).toBe('*/5 * * * *')
|
||||
expect(input).toHaveValue('*/5 * * * *')
|
||||
})
|
||||
|
||||
it('uses daily and empty cron defaults when schedule values are missing', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderPanel(createData({ frequency: undefined }))
|
||||
expect(frequencyPicker()).toHaveTextContent(
|
||||
'workflowIntegrations.nodes.triggerSchedule.frequency.daily',
|
||||
)
|
||||
expect(screen.getByRole('button', { name: /11:30 AM/ })).toBeInTheDocument()
|
||||
await user.click(cronButton())
|
||||
expect(
|
||||
screen.getByRole('textbox', { name: 'workflow.nodes.triggerSchedule.cronExpression' }),
|
||||
).toHaveValue('')
|
||||
})
|
||||
|
||||
it('saves the hourly minute selected with the slider', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { data } = renderPanel(createData({ frequency: 'hourly' }))
|
||||
screen.getByRole('slider').focus()
|
||||
await user.keyboard('{ArrowRight}')
|
||||
expect(data().visual_config?.on_minute).toBe(16)
|
||||
})
|
||||
|
||||
it.each(['weekly', 'monthly', 'hourly'] as const)(
|
||||
'disables schedule editing in read-only %s mode',
|
||||
async (frequency) => {
|
||||
const user = userEvent.setup()
|
||||
const initial = createData({ frequency })
|
||||
const { data } = renderPanel(initial, true)
|
||||
expect(cronButton()).toBeDisabled()
|
||||
await user.click(cronButton())
|
||||
expect(frequencyPicker()).toBeDisabled()
|
||||
if (frequency !== 'hourly') {
|
||||
const day = screen.getByRole('button', { name: frequency === 'weekly' ? 'Wed' : '2' })
|
||||
expect(day).toBeDisabled()
|
||||
await user.click(day)
|
||||
} else expect(screen.getByRole('slider')).toBeDisabled()
|
||||
expect(data()).toMatchObject(initial)
|
||||
},
|
||||
)
|
||||
|
||||
it('keeps cron expressions read-only when editing is denied', async () => {
|
||||
const user = userEvent.setup()
|
||||
const initial = createData({ mode: 'cron', cron_expression: '0 0 * * *' })
|
||||
const { data } = renderPanel(initial, true)
|
||||
const input = screen.getByRole('textbox', {
|
||||
name: 'workflow.nodes.triggerSchedule.cronExpression',
|
||||
})
|
||||
await user.type(input, '5')
|
||||
expect(input).toHaveValue('0 0 * * *')
|
||||
expect(data()).toMatchObject(initial)
|
||||
})
|
||||
})
|
||||
+116
@@ -0,0 +1,116 @@
|
||||
import type { ScheduleTriggerNodeType } from '../types'
|
||||
import { act, waitFor } from '@testing-library/react'
|
||||
import { seedAccountProfileQuery } from '@/test/console/account-profile'
|
||||
import { createConsoleQueryWrapper } from '@/test/console/query-data'
|
||||
import { BlockEnum } from '../../../types'
|
||||
import { renderNodeConfig } from '../../__tests__/render-node-config'
|
||||
import useConfig from '../use-config'
|
||||
|
||||
const createData = (overrides: Partial<ScheduleTriggerNodeType> = {}): ScheduleTriggerNodeType => ({
|
||||
title: 'Schedule Trigger',
|
||||
desc: '',
|
||||
type: BlockEnum.TriggerSchedule,
|
||||
mode: 'visual',
|
||||
frequency: 'daily',
|
||||
timezone: 'UTC',
|
||||
visual_config: { time: '11:30 AM', weekdays: ['mon'], on_minute: 15, monthly_days: [1] },
|
||||
...overrides,
|
||||
})
|
||||
|
||||
it('derives missing schedule defaults from the account timezone', () => {
|
||||
const { queryClient } = createConsoleQueryWrapper()
|
||||
seedAccountProfileQuery(queryClient, { timezone: 'Asia/Shanghai' })
|
||||
const { result } = renderNodeConfig(
|
||||
useConfig,
|
||||
createData({
|
||||
frequency: undefined,
|
||||
timezone: undefined,
|
||||
visual_config: undefined,
|
||||
}),
|
||||
{ queryClient },
|
||||
)
|
||||
expect(result.current.config.inputs).toEqual(
|
||||
expect.objectContaining({
|
||||
mode: 'visual',
|
||||
frequency: 'daily',
|
||||
timezone: 'Asia/Shanghai',
|
||||
visual_config: { time: '12:00 AM', weekdays: ['sun'], on_minute: 0, monthly_days: [1] },
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('persists consecutive schedule edits and clears the stale cron expression', () => {
|
||||
const { result } = renderNodeConfig(
|
||||
useConfig,
|
||||
createData({ mode: 'cron', cron_expression: '0 0 * * *' }),
|
||||
)
|
||||
act(() => result.current.config.handleModeChange('visual'))
|
||||
act(() => result.current.config.handleFrequencyChange('hourly'))
|
||||
act(() => result.current.config.handleWeekdaysChange(['tue', 'thu']))
|
||||
act(() => result.current.config.handleTimeChange('08:15 AM'))
|
||||
act(() => result.current.config.handleOnMinuteChange(45))
|
||||
expect(result.current.flow.getNode('node')?.data).toEqual(
|
||||
expect.objectContaining({
|
||||
mode: 'visual',
|
||||
frequency: 'hourly',
|
||||
cron_expression: undefined,
|
||||
visual_config: {
|
||||
time: '08:15 AM',
|
||||
weekdays: ['tue', 'thu'],
|
||||
on_minute: 45,
|
||||
monthly_days: [1],
|
||||
},
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('persists raw cron mode without visual schedule fields', () => {
|
||||
const { result } = renderNodeConfig(useConfig, createData())
|
||||
act(() => result.current.config.handleModeChange('cron'))
|
||||
act(() => result.current.config.handleCronExpressionChange('*/15 * * * *'))
|
||||
expect(result.current.flow.getNode('node')?.data).toEqual(
|
||||
expect.objectContaining({
|
||||
mode: 'cron',
|
||||
cron_expression: '*/15 * * * *',
|
||||
frequency: undefined,
|
||||
visual_config: undefined,
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('saves the profile timezone when the node has none, so the backend does not fall back to UTC', async () => {
|
||||
const { queryClient } = createConsoleQueryWrapper()
|
||||
seedAccountProfileQuery(queryClient, { timezone: 'Asia/Shanghai' })
|
||||
const { result } = renderNodeConfig(useConfig, createData({ timezone: undefined }), {
|
||||
queryClient,
|
||||
})
|
||||
await waitFor(() => {
|
||||
expect(result.current.flow.getNode('node')?.data).toEqual(
|
||||
expect.objectContaining({ timezone: 'Asia/Shanghai' }),
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
it('does not overwrite a timezone that is already saved', async () => {
|
||||
const { queryClient } = createConsoleQueryWrapper()
|
||||
seedAccountProfileQuery(queryClient, { timezone: 'Asia/Shanghai' })
|
||||
const { result } = renderNodeConfig(useConfig, createData({ timezone: 'Europe/Berlin' }), {
|
||||
queryClient,
|
||||
})
|
||||
await new Promise((resolve) => setTimeout(resolve, 0))
|
||||
expect(result.current.flow.getNode('node')?.data).toEqual(
|
||||
expect.objectContaining({ timezone: 'Europe/Berlin' }),
|
||||
)
|
||||
})
|
||||
|
||||
it('does not save the timezone in read-only mode', async () => {
|
||||
const { queryClient } = createConsoleQueryWrapper()
|
||||
seedAccountProfileQuery(queryClient, { timezone: 'Asia/Shanghai' })
|
||||
const { result } = renderNodeConfig(useConfig, createData({ timezone: undefined }), {
|
||||
queryClient,
|
||||
initialStoreState: { isRestoring: true },
|
||||
})
|
||||
await new Promise((resolve) => setTimeout(resolve, 0))
|
||||
expect(result.current.config.readOnly).toBe(true)
|
||||
expect(result.current.flow.getNode('node')?.data.timezone).toBeUndefined()
|
||||
})
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
import { render, screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import FrequencySelector from '../frequency-selector'
|
||||
|
||||
describe('trigger-schedule/frequency-selector', () => {
|
||||
it('selects a new frequency from the dropdown options', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onChange = vi.fn()
|
||||
|
||||
render(<FrequencySelector frequency="daily" onChange={onChange} />)
|
||||
|
||||
const trigger = screen.getByRole('combobox')
|
||||
await user.click(trigger)
|
||||
|
||||
await user.click(
|
||||
await screen.findByRole('option', {
|
||||
name: 'workflowIntegrations.nodes.triggerSchedule.frequency.weekly',
|
||||
}),
|
||||
)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(onChange).toHaveBeenCalledWith('weekly')
|
||||
})
|
||||
})
|
||||
})
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import ModeToggle from '../mode-toggle'
|
||||
|
||||
describe('trigger-schedule/mode-toggle', () => {
|
||||
it('toggles the mode from visual to cron', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onChange = vi.fn()
|
||||
|
||||
render(<ModeToggle mode="visual" onChange={onChange} />)
|
||||
|
||||
await user.click(screen.getByRole('button'))
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith('cron')
|
||||
})
|
||||
|
||||
it('toggles the mode from cron back to visual', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onChange = vi.fn()
|
||||
|
||||
render(<ModeToggle mode="cron" onChange={onChange} />)
|
||||
|
||||
await user.click(screen.getByRole('button'))
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith('visual')
|
||||
})
|
||||
})
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import MonthlyDaysSelector from '../monthly-days-selector'
|
||||
|
||||
describe('trigger-schedule/monthly-days-selector', () => {
|
||||
it('toggles monthly days and shows the day-31 warning', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onChange = vi.fn()
|
||||
|
||||
render(<MonthlyDaysSelector selectedDays={[31]} onChange={onChange} />)
|
||||
|
||||
expect(
|
||||
screen.getByText('workflowIntegrations.nodes.triggerSchedule.lastDayTooltip'),
|
||||
).toBeInTheDocument()
|
||||
|
||||
await user.click(
|
||||
screen.getByRole('button', {
|
||||
name: 'workflowIntegrations.nodes.triggerSchedule.lastDay',
|
||||
pressed: false,
|
||||
}),
|
||||
)
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith([31, 'last'])
|
||||
})
|
||||
|
||||
it('keeps the clicked day selected when removing the last selected day', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onChange = vi.fn()
|
||||
|
||||
render(<MonthlyDaysSelector selectedDays={[31]} onChange={onChange} />)
|
||||
|
||||
expect(
|
||||
screen.getByRole('group', { name: 'workflowIntegrations.nodes.triggerSchedule.days' }),
|
||||
).toBeInTheDocument()
|
||||
await user.click(screen.getByRole('button', { name: '31', pressed: true }))
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith([31])
|
||||
})
|
||||
})
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
import type { ScheduleTriggerNodeType } from '../../types'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import { BlockEnum } from '../../../../types'
|
||||
import NextExecutionTimes from '../next-execution-times'
|
||||
|
||||
const createData = (overrides: Partial<ScheduleTriggerNodeType> = {}): ScheduleTriggerNodeType => ({
|
||||
title: 'Schedule Trigger',
|
||||
desc: '',
|
||||
type: BlockEnum.TriggerSchedule,
|
||||
mode: 'visual',
|
||||
frequency: 'daily',
|
||||
timezone: 'UTC',
|
||||
visual_config: {
|
||||
time: '11:30 AM',
|
||||
weekdays: ['mon'],
|
||||
on_minute: 15,
|
||||
monthly_days: [1],
|
||||
},
|
||||
...overrides,
|
||||
})
|
||||
|
||||
describe('trigger-schedule/next-execution-times', () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers()
|
||||
vi.setSystemTime(new Date('2026-01-15T12:00:00Z'))
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('renders the upcoming execution times when the schedule is valid', () => {
|
||||
render(<NextExecutionTimes data={createData()} />)
|
||||
|
||||
expect(
|
||||
screen.getByText('workflowIntegrations.nodes.triggerSchedule.nextExecutionTimes'),
|
||||
).toBeInTheDocument()
|
||||
expect(screen.getByText(/January 16, 2026, 11:30\sAM/)).toBeInTheDocument()
|
||||
expect(screen.getByText(/January 20, 2026, 11:30\sAM/)).toBeInTheDocument()
|
||||
expect(screen.getAllByText(/January \d+, 2026, 11:30\sAM/)).toHaveLength(5)
|
||||
})
|
||||
|
||||
it('hides upcoming execution times when frequency is missing or cron is invalid', () => {
|
||||
const { rerender, container } = render(
|
||||
<NextExecutionTimes data={createData({ frequency: undefined })} />,
|
||||
)
|
||||
|
||||
expect(container).toBeEmptyDOMElement()
|
||||
|
||||
rerender(
|
||||
<NextExecutionTimes data={createData({ mode: 'cron', cron_expression: 'bad cron' })} />,
|
||||
)
|
||||
expect(container).toBeEmptyDOMElement()
|
||||
})
|
||||
})
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import OnMinuteSelector from '../on-minute-selector'
|
||||
|
||||
describe('trigger-schedule/on-minute-selector', () => {
|
||||
it('changes the hourly minute through the slider', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onChange = vi.fn()
|
||||
|
||||
const { rerender } = render(<OnMinuteSelector value={15} onChange={onChange} />)
|
||||
|
||||
const slider = screen.getByRole('slider', {
|
||||
name: 'workflowIntegrations.nodes.triggerSchedule.onMinute',
|
||||
})
|
||||
expect(screen.getByRole('status')).toHaveTextContent('15')
|
||||
slider.focus()
|
||||
await user.keyboard('{ArrowRight}')
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith(16, expect.anything())
|
||||
rerender(<OnMinuteSelector value={16} onChange={onChange} />)
|
||||
expect(screen.getByRole('status')).toHaveTextContent('16')
|
||||
})
|
||||
})
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import WeekdaySelector from '../weekday-selector'
|
||||
|
||||
describe('trigger-schedule/weekday-selector', () => {
|
||||
it('keeps at least one weekday selected', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onChange = vi.fn()
|
||||
|
||||
render(<WeekdaySelector selectedDays={['mon']} onChange={onChange} />)
|
||||
|
||||
expect(
|
||||
screen.getByRole('group', { name: 'workflow.nodes.triggerSchedule.weekdays' }),
|
||||
).toBeInTheDocument()
|
||||
await user.click(screen.getByRole('button', { name: 'Mon', pressed: true }))
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith(['mon'])
|
||||
})
|
||||
|
||||
it('adds a new weekday when the day is not selected yet', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onChange = vi.fn()
|
||||
|
||||
render(<WeekdaySelector selectedDays={[]} onChange={onChange} />)
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Tue' }))
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith(['tue'])
|
||||
})
|
||||
})
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
import type { ScheduleFrequency } from '../types'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectGroup,
|
||||
SelectGroupLabel,
|
||||
SelectItem,
|
||||
SelectItemIndicator,
|
||||
SelectItemText,
|
||||
SelectLabel,
|
||||
SelectTrigger,
|
||||
} from '@langgenius/dify-ui/select'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
type FrequencyOption = {
|
||||
value: ScheduleFrequency
|
||||
name: string
|
||||
}
|
||||
|
||||
type FrequencySelectorProps = {
|
||||
disabled?: boolean
|
||||
frequency: ScheduleFrequency
|
||||
onChange: (frequency: ScheduleFrequency) => void
|
||||
}
|
||||
|
||||
const FrequencySelector = ({ frequency, onChange, disabled }: FrequencySelectorProps) => {
|
||||
const { t } = useTranslation(['workflow', 'workflowIntegrations'])
|
||||
const groupLabel = t(($) => $['nodes.triggerSchedule.frequency.label'], {
|
||||
ns: 'workflowIntegrations',
|
||||
})
|
||||
const fieldLabel = t(($) => $['nodes.triggerSchedule.frequencyLabel'], { ns: 'workflow' })
|
||||
|
||||
const frequencies: FrequencyOption[] = [
|
||||
{
|
||||
value: 'hourly',
|
||||
name: t(($) => $['nodes.triggerSchedule.frequency.hourly'], { ns: 'workflowIntegrations' }),
|
||||
},
|
||||
{
|
||||
value: 'daily',
|
||||
name: t(($) => $['nodes.triggerSchedule.frequency.daily'], { ns: 'workflowIntegrations' }),
|
||||
},
|
||||
{
|
||||
value: 'weekly',
|
||||
name: t(($) => $['nodes.triggerSchedule.frequency.weekly'], { ns: 'workflowIntegrations' }),
|
||||
},
|
||||
{
|
||||
value: 'monthly',
|
||||
name: t(($) => $['nodes.triggerSchedule.frequency.monthly'], { ns: 'workflowIntegrations' }),
|
||||
},
|
||||
]
|
||||
const selectedFrequency = frequencies.find((item) => item.value === frequency)
|
||||
|
||||
const handleFrequencyChange = (value: string | null) => {
|
||||
const selected = frequencies.find((item) => item.value === value)
|
||||
if (selected) onChange(selected.value)
|
||||
}
|
||||
|
||||
return (
|
||||
<Select
|
||||
disabled={disabled}
|
||||
key={`${frequency}-${groupLabel}`}
|
||||
value={frequency}
|
||||
onValueChange={handleFrequencyChange}
|
||||
>
|
||||
<div className="flex flex-col">
|
||||
<SelectLabel className="text-xs">{fieldLabel}</SelectLabel>
|
||||
<SelectTrigger className="w-full py-2">
|
||||
{selectedFrequency?.name ??
|
||||
t(($) => $['nodes.triggerSchedule.selectFrequency'], { ns: 'workflowIntegrations' })}
|
||||
</SelectTrigger>
|
||||
</div>
|
||||
<SelectContent>
|
||||
<SelectGroup>
|
||||
<SelectGroupLabel>{groupLabel}</SelectGroupLabel>
|
||||
{frequencies.map((item) => (
|
||||
<SelectItem key={item.value} value={item.value}>
|
||||
<SelectItemText>{item.name}</SelectItemText>
|
||||
<SelectItemIndicator />
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectGroup>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
)
|
||||
}
|
||||
|
||||
export default FrequencySelector
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
import type { ScheduleMode } from '../types'
|
||||
import { cn } from '@langgenius/dify-ui/cn'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
type ModeToggleProps = {
|
||||
disabled?: boolean
|
||||
mode: ScheduleMode
|
||||
onChange: (mode: ScheduleMode) => void
|
||||
}
|
||||
|
||||
const ModeToggle = ({ mode, onChange, disabled }: ModeToggleProps) => {
|
||||
const { t } = useTranslation(['workflowIntegrations'])
|
||||
|
||||
const handleToggle = () => {
|
||||
const newMode = mode === 'visual' ? 'cron' : 'visual'
|
||||
onChange(newMode)
|
||||
}
|
||||
|
||||
const currentText =
|
||||
mode === 'visual'
|
||||
? t(($) => $['nodes.triggerSchedule.useCronExpression'], { ns: 'workflowIntegrations' })
|
||||
: t(($) => $['nodes.triggerSchedule.useVisualPicker'], { ns: 'workflowIntegrations' })
|
||||
|
||||
const iconClassName =
|
||||
mode === 'visual'
|
||||
? 'i-custom-vender-workflow-asterisk'
|
||||
: 'i-custom-vender-workflow-calendar-check-line'
|
||||
|
||||
return (
|
||||
<button
|
||||
disabled={disabled}
|
||||
type="button"
|
||||
onClick={handleToggle}
|
||||
className="flex cursor-pointer items-center gap-1 rounded-lg px-2 py-1 text-sm text-text-secondary hover:bg-state-base-hover"
|
||||
>
|
||||
<span aria-hidden className={cn(iconClassName, 'size-4')} />
|
||||
<span>{currentText}</span>
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
export default ModeToggle
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
import { cn } from '@langgenius/dify-ui/cn'
|
||||
import { Fieldset, FieldsetLegend } from '@langgenius/dify-ui/fieldset'
|
||||
import { Infotip, InfotipContent, InfotipTrigger } from '@langgenius/dify-ui/infotip'
|
||||
import { Toggle } from '@langgenius/dify-ui/toggle'
|
||||
import * as React from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
const dayToggleClassName =
|
||||
'rounded-lg border border-divider-subtle bg-components-option-card-option-bg py-1 text-xs text-text-tertiary outline-state-accent-solid transition-colors hover:border-divider-regular hover:text-text-secondary focus-visible:ring-0 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-solid data-pressed:border-util-colors-blue-brand-blue-brand-600 data-pressed:text-text-secondary data-pressed:hover:border-util-colors-blue-brand-blue-brand-600'
|
||||
|
||||
type MonthlyDaysSelectorProps = {
|
||||
disabled?: boolean
|
||||
selectedDays: (number | 'last')[]
|
||||
onChange: (days: (number | 'last')[]) => void
|
||||
}
|
||||
|
||||
const MonthlyDaysSelector = ({ selectedDays, onChange, disabled }: MonthlyDaysSelectorProps) => {
|
||||
const lastDayLabelId = React.useId()
|
||||
|
||||
const { t } = useTranslation(['workflowIntegrations'])
|
||||
|
||||
const handleDayClick = (day: number | 'last') => {
|
||||
const current = selectedDays || []
|
||||
const newSelected = current.includes(day) ? current.filter((d) => d !== day) : [...current, day]
|
||||
// Ensure at least one day is selected (consistent with WeekdaySelector)
|
||||
onChange(newSelected.length > 0 ? newSelected : [day])
|
||||
}
|
||||
|
||||
const isDaySelected = (day: number | 'last') => selectedDays?.includes(day) || false
|
||||
|
||||
const days = Array.from({ length: 31 }, (_, i) => i + 1)
|
||||
const rows = [
|
||||
days.slice(0, 7),
|
||||
days.slice(7, 14),
|
||||
days.slice(14, 21),
|
||||
days.slice(21, 28),
|
||||
[29, 30, 31, 'last' as const],
|
||||
]
|
||||
|
||||
return (
|
||||
<Fieldset className="space-y-2">
|
||||
<FieldsetLegend className="mb-2 py-0 text-xs font-medium text-text-tertiary">
|
||||
{t(($) => $['nodes.triggerSchedule.days'], { ns: 'workflowIntegrations' })}
|
||||
</FieldsetLegend>
|
||||
|
||||
<div className="space-y-1.5">
|
||||
{rows.map((row, rowIndex) => (
|
||||
<div key={rowIndex} className="grid grid-cols-7 gap-1.5">
|
||||
{row.map((day) =>
|
||||
day === 'last' ? (
|
||||
<div key={day} className="relative col-span-2 min-w-0">
|
||||
<Toggle
|
||||
disabled={disabled}
|
||||
id={lastDayLabelId}
|
||||
pressed={isDaySelected(day)}
|
||||
onPressedChange={() => handleDayClick(day)}
|
||||
className={cn(dayToggleClassName, 'w-full pe-4')}
|
||||
>
|
||||
{t(($) => $['nodes.triggerSchedule.lastDay'], { ns: 'workflowIntegrations' })}
|
||||
</Toggle>
|
||||
<Infotip>
|
||||
<InfotipTrigger
|
||||
aria-labelledby={lastDayLabelId}
|
||||
className="absolute inset-e-1 top-1/2 size-3 -translate-y-1/2"
|
||||
iconSize="small"
|
||||
/>
|
||||
<InfotipContent aria-labelledby={lastDayLabelId}>
|
||||
{t(($) => $['nodes.triggerSchedule.lastDayTooltip'], {
|
||||
ns: 'workflowIntegrations',
|
||||
})}
|
||||
</InfotipContent>
|
||||
</Infotip>
|
||||
</div>
|
||||
) : (
|
||||
<Toggle
|
||||
disabled={disabled}
|
||||
key={day}
|
||||
pressed={isDaySelected(day)}
|
||||
onPressedChange={() => handleDayClick(day)}
|
||||
className={dayToggleClassName}
|
||||
>
|
||||
{day}
|
||||
</Toggle>
|
||||
),
|
||||
)}
|
||||
{/* Fill empty cells in the last row (Last day takes 2 cols, so need 1 less) */}
|
||||
{rowIndex === rows.length - 1 &&
|
||||
Array.from({ length: 7 - row.length - 1 }, (_, i) => (
|
||||
<div key={`empty-${i}`} className="invisible"></div>
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Warning message for day 31 - aligned with grid */}
|
||||
{selectedDays?.includes(31) && (
|
||||
<div className="mt-1.5 grid grid-cols-7 gap-1.5">
|
||||
<div className="col-span-7 text-xs text-text-tertiary">
|
||||
{t(($) => $['nodes.triggerSchedule.lastDayTooltip'], { ns: 'workflowIntegrations' })}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</Fieldset>
|
||||
)
|
||||
}
|
||||
|
||||
export default MonthlyDaysSelector
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
import type { ScheduleTriggerNodeType } from '../types'
|
||||
import * as React from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { getFormattedExecutionTimes } from '../utils/execution-time-calculator'
|
||||
|
||||
type NextExecutionTimesProps = {
|
||||
data: ScheduleTriggerNodeType
|
||||
}
|
||||
|
||||
const NextExecutionTimes = ({ data }: NextExecutionTimesProps) => {
|
||||
const { t } = useTranslation(['workflowIntegrations'])
|
||||
|
||||
if (!data.frequency) return null
|
||||
|
||||
const executionTimes = getFormattedExecutionTimes(data, 5)
|
||||
|
||||
if (executionTimes.length === 0) return null
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<div className="text-xs font-medium text-text-secondary">
|
||||
{t(($) => $['nodes.triggerSchedule.nextExecutionTimes'], { ns: 'workflowIntegrations' })}
|
||||
</div>
|
||||
<div className="flex min-h-20 flex-col rounded-xl bg-components-input-bg-normal py-2">
|
||||
{executionTimes.map((time, index) => (
|
||||
<div key={index} className="flex items-baseline text-xs">
|
||||
<span className="w-6 text-right font-mono leading-[150%] font-normal tracking-wider text-text-quaternary select-none">
|
||||
{String(index + 1).padStart(2, '0')}
|
||||
</span>
|
||||
<span className="pr-3 pl-2 font-mono leading-[150%] font-normal tracking-wider text-text-secondary">
|
||||
{time}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default NextExecutionTimes
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
import {
|
||||
Slider,
|
||||
SliderControl,
|
||||
SliderIndicator,
|
||||
SliderLabel,
|
||||
SliderThumb,
|
||||
SliderTrack,
|
||||
SliderValue,
|
||||
} from '@langgenius/dify-ui/slider'
|
||||
import * as React from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
type OnMinuteSelectorProps = {
|
||||
disabled?: boolean
|
||||
value?: number
|
||||
onChange: (value: number) => void
|
||||
}
|
||||
|
||||
const OnMinuteSelector = ({ value = 0, onChange, disabled }: OnMinuteSelectorProps) => {
|
||||
const { t } = useTranslation(['workflowIntegrations'])
|
||||
|
||||
return (
|
||||
<Slider
|
||||
disabled={disabled}
|
||||
className="flex flex-col"
|
||||
value={value}
|
||||
min={0}
|
||||
max={59}
|
||||
step={1}
|
||||
onValueChange={onChange}
|
||||
>
|
||||
<SliderLabel className="text-xs">
|
||||
{t(($) => $['nodes.triggerSchedule.onMinute'], { ns: 'workflowIntegrations' })}
|
||||
</SliderLabel>
|
||||
<div className="relative flex h-8 items-center rounded-lg bg-components-input-bg-normal">
|
||||
<SliderValue className="flex h-full w-12 shrink-0 items-center justify-center text-[13px] text-components-input-text-filled" />
|
||||
<div className="absolute top-0 left-12 h-full w-px bg-components-panel-bg"></div>
|
||||
<div className="flex h-full grow items-center pr-3 pl-4">
|
||||
<SliderControl>
|
||||
<SliderTrack>
|
||||
<SliderIndicator />
|
||||
<SliderThumb />
|
||||
</SliderTrack>
|
||||
</SliderControl>
|
||||
</div>
|
||||
</div>
|
||||
</Slider>
|
||||
)
|
||||
}
|
||||
|
||||
export default OnMinuteSelector
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
import { Fieldset, FieldsetLegend } from '@langgenius/dify-ui/fieldset'
|
||||
import { Toggle } from '@langgenius/dify-ui/toggle'
|
||||
import * as React from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
type WeekdaySelectorProps = {
|
||||
disabled?: boolean
|
||||
selectedDays: string[]
|
||||
onChange: (days: string[]) => void
|
||||
}
|
||||
|
||||
const WeekdaySelector = ({ selectedDays, onChange, disabled }: WeekdaySelectorProps) => {
|
||||
const { t } = useTranslation(['workflow'])
|
||||
|
||||
const weekdays = [
|
||||
{ key: 'sun', label: 'Sun' },
|
||||
{ key: 'mon', label: 'Mon' },
|
||||
{ key: 'tue', label: 'Tue' },
|
||||
{ key: 'wed', label: 'Wed' },
|
||||
{ key: 'thu', label: 'Thu' },
|
||||
{ key: 'fri', label: 'Fri' },
|
||||
{ key: 'sat', label: 'Sat' },
|
||||
]
|
||||
|
||||
const handleDaySelect = (dayKey: string) => {
|
||||
const current = selectedDays || []
|
||||
const newSelected = current.includes(dayKey)
|
||||
? current.filter((d) => d !== dayKey)
|
||||
: [...current, dayKey]
|
||||
onChange(newSelected.length > 0 ? newSelected : [dayKey])
|
||||
}
|
||||
|
||||
const isDaySelected = (dayKey: string) => selectedDays.includes(dayKey)
|
||||
|
||||
return (
|
||||
<Fieldset className="space-y-2">
|
||||
<FieldsetLegend className="mb-2 py-0 text-xs font-medium text-text-tertiary">
|
||||
{t(($) => $['nodes.triggerSchedule.weekdays'], { ns: 'workflow' })}
|
||||
</FieldsetLegend>
|
||||
<div className="flex gap-1.5">
|
||||
{weekdays.map((day) => (
|
||||
<Toggle
|
||||
disabled={disabled}
|
||||
key={day.key}
|
||||
pressed={isDaySelected(day.key)}
|
||||
onPressedChange={() => handleDaySelect(day.key)}
|
||||
className="flex-1 rounded-lg border border-divider-subtle bg-components-option-card-option-bg py-1 text-xs text-text-tertiary outline-state-accent-solid transition-colors hover:border-divider-regular hover:text-text-secondary focus-visible:ring-0 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-solid data-pressed:border-util-colors-blue-brand-blue-brand-600 data-pressed:text-text-secondary data-pressed:hover:border-util-colors-blue-brand-blue-brand-600"
|
||||
>
|
||||
{day.label}
|
||||
</Toggle>
|
||||
))}
|
||||
</div>
|
||||
</Fieldset>
|
||||
)
|
||||
}
|
||||
|
||||
export default WeekdaySelector
|
||||
@@ -0,0 +1,19 @@
|
||||
import type { ScheduleTriggerNodeType } from './types'
|
||||
|
||||
export const getDefaultScheduleConfig = (): Partial<ScheduleTriggerNodeType> => ({
|
||||
mode: 'visual',
|
||||
frequency: 'daily',
|
||||
visual_config: {
|
||||
time: '12:00 AM',
|
||||
weekdays: ['sun'],
|
||||
on_minute: 0,
|
||||
monthly_days: [1],
|
||||
},
|
||||
})
|
||||
|
||||
export const getDefaultVisualConfig = () => ({
|
||||
time: '12:00 AM',
|
||||
weekdays: ['sun'],
|
||||
on_minute: 0,
|
||||
monthly_days: [1],
|
||||
})
|
||||
@@ -0,0 +1,211 @@
|
||||
import type { TFunction } from 'i18next'
|
||||
import type { NodeDefault } from '../../types'
|
||||
import type { ScheduleTriggerNodeType } from './types'
|
||||
import { BlockEnum } from '../../types'
|
||||
import { genNodeMetaData } from '../../utils'
|
||||
import { getDefaultScheduleConfig } from './constants'
|
||||
import { isValidCronExpression } from './utils/cron-parser'
|
||||
import { getNextExecutionTimes } from './utils/execution-time-calculator'
|
||||
|
||||
const isValidTimeFormat = (time: string): boolean => {
|
||||
const timeRegex = /^(?:0?\d|1[0-2]):[0-5]\d (?:AM|PM)$/
|
||||
if (!timeRegex.test(time)) return false
|
||||
|
||||
const [timePart, period] = time.split(' ')
|
||||
const [hour, minute] = timePart!.split(':')
|
||||
const hourNum = Number.parseInt(hour!, 10)
|
||||
const minuteNum = Number.parseInt(minute!, 10)
|
||||
|
||||
return (
|
||||
hourNum >= 1 &&
|
||||
hourNum <= 12 &&
|
||||
minuteNum >= 0 &&
|
||||
minuteNum <= 59 &&
|
||||
['AM', 'PM'].includes(period!)
|
||||
)
|
||||
}
|
||||
|
||||
const validateHourlyConfig = (
|
||||
config: NonNullable<ScheduleTriggerNodeType['visual_config']>,
|
||||
t: TFunction<['workflow']>,
|
||||
): string => {
|
||||
if (config.on_minute === undefined || config.on_minute < 0 || config.on_minute > 59)
|
||||
return t(($) => $['nodes.triggerSchedule.invalidOnMinute'], { ns: 'workflow' })
|
||||
|
||||
return ''
|
||||
}
|
||||
|
||||
const validateDailyConfig = (
|
||||
config: NonNullable<ScheduleTriggerNodeType['visual_config']>,
|
||||
t: TFunction<['workflow']>,
|
||||
): string => {
|
||||
const i18nPrefix = 'errorMsg'
|
||||
|
||||
if (!config.time)
|
||||
return t(($) => $[`${i18nPrefix}.fieldRequired`], {
|
||||
ns: 'workflow',
|
||||
field: t(($) => $['nodes.triggerSchedule.time'], { ns: 'workflow' }),
|
||||
})
|
||||
|
||||
if (!isValidTimeFormat(config.time))
|
||||
return t(($) => $['nodes.triggerSchedule.invalidTimeFormat'], { ns: 'workflow' })
|
||||
|
||||
return ''
|
||||
}
|
||||
|
||||
const validateWeeklyConfig = (
|
||||
config: NonNullable<ScheduleTriggerNodeType['visual_config']>,
|
||||
t: TFunction<['workflow']>,
|
||||
): string => {
|
||||
const dailyError = validateDailyConfig(config, t)
|
||||
if (dailyError) return dailyError
|
||||
|
||||
const i18nPrefix = 'errorMsg'
|
||||
|
||||
if (!config.weekdays || config.weekdays.length === 0)
|
||||
return t(($) => $[`${i18nPrefix}.fieldRequired`], {
|
||||
ns: 'workflow',
|
||||
field: t(($) => $['nodes.triggerSchedule.weekdays'], { ns: 'workflow' }),
|
||||
})
|
||||
|
||||
const validWeekdays = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat']
|
||||
for (const day of config.weekdays) {
|
||||
if (!validWeekdays.includes(day))
|
||||
return t(($) => $['nodes.triggerSchedule.invalidWeekday'], { ns: 'workflow', weekday: day })
|
||||
}
|
||||
|
||||
return ''
|
||||
}
|
||||
|
||||
const validateMonthlyConfig = (
|
||||
config: NonNullable<ScheduleTriggerNodeType['visual_config']>,
|
||||
t: TFunction<['workflow']>,
|
||||
): string => {
|
||||
const dailyError = validateDailyConfig(config, t)
|
||||
if (dailyError) return dailyError
|
||||
|
||||
const i18nPrefix = 'errorMsg'
|
||||
|
||||
const getMonthlyDays = (): (number | 'last')[] => {
|
||||
if (Array.isArray(config.monthly_days) && config.monthly_days.length > 0)
|
||||
return config.monthly_days
|
||||
|
||||
return []
|
||||
}
|
||||
|
||||
const monthlyDays = getMonthlyDays()
|
||||
|
||||
if (monthlyDays.length === 0)
|
||||
return t(($) => $[`${i18nPrefix}.fieldRequired`], {
|
||||
ns: 'workflow',
|
||||
field: t(($) => $['nodes.triggerSchedule.monthlyDay'], { ns: 'workflow' }),
|
||||
})
|
||||
|
||||
for (const day of monthlyDays) {
|
||||
if (day !== 'last' && (typeof day !== 'number' || day < 1 || day > 31))
|
||||
return t(($) => $['nodes.triggerSchedule.invalidMonthlyDay'], { ns: 'workflow' })
|
||||
}
|
||||
|
||||
return ''
|
||||
}
|
||||
|
||||
const validateVisualConfig = (
|
||||
payload: ScheduleTriggerNodeType,
|
||||
t: TFunction<['workflow']>,
|
||||
): string => {
|
||||
const i18nPrefix = 'errorMsg'
|
||||
const { visual_config } = payload
|
||||
|
||||
if (!visual_config)
|
||||
return t(($) => $[`${i18nPrefix}.fieldRequired`], {
|
||||
ns: 'workflow',
|
||||
field: t(($) => $['nodes.triggerSchedule.visualConfig'], { ns: 'workflow' }),
|
||||
})
|
||||
|
||||
switch (payload.frequency) {
|
||||
case 'hourly':
|
||||
return validateHourlyConfig(visual_config, t)
|
||||
case 'daily':
|
||||
return validateDailyConfig(visual_config, t)
|
||||
case 'weekly':
|
||||
return validateWeeklyConfig(visual_config, t)
|
||||
case 'monthly':
|
||||
return validateMonthlyConfig(visual_config, t)
|
||||
default:
|
||||
return t(($) => $['nodes.triggerSchedule.invalidFrequency'], { ns: 'workflow' })
|
||||
}
|
||||
}
|
||||
|
||||
const metaData = genNodeMetaData({
|
||||
sort: 2,
|
||||
type: BlockEnum.TriggerSchedule,
|
||||
helpLinkUri: 'trigger/schedule-trigger',
|
||||
isStart: true,
|
||||
})
|
||||
|
||||
const nodeDefault: NodeDefault<ScheduleTriggerNodeType> = {
|
||||
metaData,
|
||||
defaultValue: {
|
||||
...getDefaultScheduleConfig(),
|
||||
cron_expression: '',
|
||||
} as ScheduleTriggerNodeType,
|
||||
checkValid(payload: ScheduleTriggerNodeType, t: TFunction<['workflow']>) {
|
||||
const i18nPrefix = 'errorMsg'
|
||||
let errorMessages = ''
|
||||
if (!errorMessages && !payload.mode)
|
||||
errorMessages = t(($) => $[`${i18nPrefix}.fieldRequired`], {
|
||||
ns: 'workflow',
|
||||
field: t(($) => $['nodes.triggerSchedule.mode'], { ns: 'workflow' }),
|
||||
})
|
||||
|
||||
// Validate timezone format if provided (timezone will be auto-filled by use-config.ts if undefined)
|
||||
if (!errorMessages && payload.timezone) {
|
||||
try {
|
||||
// oxlint-disable-next-line no-new
|
||||
new Intl.DateTimeFormat(undefined, { timeZone: payload.timezone })
|
||||
} catch {
|
||||
errorMessages = t(($) => $['nodes.triggerSchedule.invalidTimezone'], { ns: 'workflow' })
|
||||
}
|
||||
}
|
||||
if (!errorMessages) {
|
||||
if (payload.mode === 'cron') {
|
||||
if (!payload.cron_expression || payload.cron_expression.trim() === '')
|
||||
errorMessages = t(($) => $[`${i18nPrefix}.fieldRequired`], {
|
||||
ns: 'workflow',
|
||||
field: t(($) => $['nodes.triggerSchedule.cronExpression'], { ns: 'workflow' }),
|
||||
})
|
||||
else if (!isValidCronExpression(payload.cron_expression))
|
||||
errorMessages = t(($) => $['nodes.triggerSchedule.invalidCronExpression'], {
|
||||
ns: 'workflow',
|
||||
})
|
||||
} else if (payload.mode === 'visual') {
|
||||
if (!payload.frequency)
|
||||
errorMessages = t(($) => $[`${i18nPrefix}.fieldRequired`], {
|
||||
ns: 'workflow',
|
||||
field: t(($) => $['nodes.triggerSchedule.frequencyLabel'], { ns: 'workflow' }),
|
||||
})
|
||||
else errorMessages = validateVisualConfig(payload, t)
|
||||
}
|
||||
}
|
||||
if (!errorMessages) {
|
||||
try {
|
||||
const nextTimes = getNextExecutionTimes(payload, 1)
|
||||
if (nextTimes.length === 0)
|
||||
errorMessages = t(($) => $['nodes.triggerSchedule.noValidExecutionTime'], {
|
||||
ns: 'workflow',
|
||||
})
|
||||
} catch {
|
||||
errorMessages = t(($) => $['nodes.triggerSchedule.executionTimeCalculationError'], {
|
||||
ns: 'workflow',
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
isValid: !errorMessages,
|
||||
errorMessage: errorMessages,
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
export default nodeDefault
|
||||
@@ -0,0 +1,29 @@
|
||||
import type { FC } from 'react'
|
||||
import type { ScheduleTriggerNodeType } from './types'
|
||||
import type { NodeProps } from '@/app/components/workflow/types'
|
||||
import * as React from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { getNextExecutionTime } from './utils/execution-time-calculator'
|
||||
|
||||
const i18nPrefix = 'nodes.triggerSchedule'
|
||||
|
||||
const Node: FC<NodeProps<ScheduleTriggerNodeType>> = ({ data }) => {
|
||||
const { t } = useTranslation(['workflowIntegrations'])
|
||||
|
||||
return (
|
||||
<div className="mb-1 px-3 py-1">
|
||||
<div className="mb-1 text-2xs font-medium tracking-wide text-text-tertiary uppercase">
|
||||
{t(($) => $[`${i18nPrefix}.nextExecutionTime`], { ns: 'workflowIntegrations' })}
|
||||
</div>
|
||||
<div className="flex h-6.5 items-center rounded-md bg-workflow-block-parma-bg px-2 text-xs text-text-secondary">
|
||||
<div className="w-0 grow">
|
||||
<div className="truncate" title={getNextExecutionTime(data)}>
|
||||
{getNextExecutionTime(data)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default React.memo(Node)
|
||||
@@ -0,0 +1,148 @@
|
||||
import type { FC } from 'react'
|
||||
import type { ScheduleTriggerNodeType } from './types'
|
||||
import type { NodePanelProps } from '@/app/components/workflow/types'
|
||||
import { Field, FieldLabel } from '@langgenius/dify-ui/field'
|
||||
import { Input } from '@langgenius/dify-ui/input'
|
||||
import * as React from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import {
|
||||
TimePicker,
|
||||
TimePickerContent,
|
||||
TimePickerLabel,
|
||||
TimePickerTrigger,
|
||||
TimePickerValue,
|
||||
} from '@/app/components/base/date-time-picker/time-picker'
|
||||
import WorkflowField from '@/app/components/workflow/nodes/_base/components/field'
|
||||
import FrequencySelector from './components/frequency-selector'
|
||||
import ModeToggle from './components/mode-toggle'
|
||||
import MonthlyDaysSelector from './components/monthly-days-selector'
|
||||
import NextExecutionTimes from './components/next-execution-times'
|
||||
import OnMinuteSelector from './components/on-minute-selector'
|
||||
import WeekdaySelector from './components/weekday-selector'
|
||||
import useConfig from './use-config'
|
||||
import { formatClockTime, parseClockTime } from './utils/clock-time'
|
||||
|
||||
const i18nPrefix = 'nodes.triggerSchedule'
|
||||
|
||||
const Panel: FC<NodePanelProps<ScheduleTriggerNodeType>> = ({ id, data }) => {
|
||||
const { t } = useTranslation(['workflow', 'workflowIntegrations'])
|
||||
const {
|
||||
readOnly,
|
||||
inputs,
|
||||
setInputs,
|
||||
handleModeChange,
|
||||
handleFrequencyChange,
|
||||
handleCronExpressionChange,
|
||||
handleWeekdaysChange,
|
||||
handleTimeChange,
|
||||
handleOnMinuteChange,
|
||||
} = useConfig(id, data)
|
||||
|
||||
return (
|
||||
<div className="mt-2">
|
||||
<div className="space-y-4 px-4 pt-2 pb-3">
|
||||
<WorkflowField
|
||||
title={t(($) => $[`${i18nPrefix}.title`], { ns: 'workflowIntegrations' })}
|
||||
operations={
|
||||
<ModeToggle disabled={readOnly} mode={inputs.mode} onChange={handleModeChange} />
|
||||
}
|
||||
>
|
||||
<div className="space-y-3">
|
||||
{inputs.mode === 'visual' && (
|
||||
<div className="space-y-3">
|
||||
<div className="grid grid-cols-3 gap-3">
|
||||
<FrequencySelector
|
||||
disabled={readOnly}
|
||||
frequency={inputs.frequency || 'daily'}
|
||||
onChange={handleFrequencyChange}
|
||||
/>
|
||||
<div className="col-span-2">
|
||||
{inputs.frequency === 'hourly' ? (
|
||||
<OnMinuteSelector
|
||||
disabled={readOnly}
|
||||
value={inputs.visual_config?.on_minute}
|
||||
onChange={handleOnMinuteChange}
|
||||
/>
|
||||
) : (
|
||||
<div className="flex flex-col">
|
||||
<TimePicker
|
||||
readOnly={readOnly}
|
||||
timeZone={inputs.timezone}
|
||||
value={parseClockTime(inputs.visual_config?.time || '12:00 AM')}
|
||||
onValueChange={(time) => {
|
||||
if (time) handleTimeChange(formatClockTime(time))
|
||||
}}
|
||||
>
|
||||
<TimePickerLabel className="text-xs">
|
||||
{t(($) => $['nodes.triggerSchedule.time'], { ns: 'workflow' })}
|
||||
</TimePickerLabel>
|
||||
<TimePickerTrigger className="w-full">
|
||||
<TimePickerValue className="flex flex-1 items-center justify-between">
|
||||
{(value) => (
|
||||
<>
|
||||
{value}
|
||||
<span className="text-text-tertiary">{inputs.timezone}</span>
|
||||
</>
|
||||
)}
|
||||
</TimePickerValue>
|
||||
</TimePickerTrigger>
|
||||
<TimePickerContent />
|
||||
</TimePicker>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{inputs.frequency === 'weekly' && (
|
||||
<WeekdaySelector
|
||||
disabled={readOnly}
|
||||
selectedDays={inputs.visual_config?.weekdays || []}
|
||||
onChange={handleWeekdaysChange}
|
||||
/>
|
||||
)}
|
||||
|
||||
{inputs.frequency === 'monthly' && (
|
||||
<MonthlyDaysSelector
|
||||
disabled={readOnly}
|
||||
selectedDays={inputs.visual_config?.monthly_days || [1]}
|
||||
onChange={(days) => {
|
||||
const newInputs = {
|
||||
...inputs,
|
||||
visual_config: {
|
||||
...inputs.visual_config,
|
||||
monthly_days: days,
|
||||
},
|
||||
}
|
||||
setInputs(newInputs)
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{inputs.mode === 'cron' && (
|
||||
<Field className="gap-0">
|
||||
<FieldLabel className="text-xs">
|
||||
{t(($) => $['nodes.triggerSchedule.cronExpression'], { ns: 'workflow' })}
|
||||
</FieldLabel>
|
||||
<Input
|
||||
readOnly={readOnly}
|
||||
value={inputs.cron_expression || ''}
|
||||
onValueChange={(value) => handleCronExpressionChange(value)}
|
||||
placeholder="0 0 * * *"
|
||||
className="font-mono"
|
||||
/>
|
||||
</Field>
|
||||
)}
|
||||
</div>
|
||||
</WorkflowField>
|
||||
|
||||
<div className="border-t border-divider-subtle"></div>
|
||||
|
||||
<NextExecutionTimes data={inputs} />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default React.memo(Panel)
|
||||
@@ -0,0 +1,20 @@
|
||||
import type { CommonNodeType } from '@/app/components/workflow/types'
|
||||
|
||||
export type ScheduleMode = 'visual' | 'cron'
|
||||
|
||||
export type ScheduleFrequency = 'hourly' | 'daily' | 'weekly' | 'monthly'
|
||||
|
||||
type VisualConfig = {
|
||||
time?: string
|
||||
weekdays?: string[]
|
||||
on_minute?: number
|
||||
monthly_days?: (number | 'last')[]
|
||||
}
|
||||
|
||||
export type ScheduleTriggerNodeType = CommonNodeType & {
|
||||
mode: ScheduleMode
|
||||
frequency?: ScheduleFrequency
|
||||
cron_expression?: string
|
||||
visual_config?: VisualConfig
|
||||
timezone?: string
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
import type { ScheduleFrequency, ScheduleMode, ScheduleTriggerNodeType } from './types'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { useCallback, useEffect, useMemo } from 'react'
|
||||
import useNodeCrud from '@/app/components/workflow/nodes/_base/hooks/use-node-crud'
|
||||
import { userProfileQueryOptions } from '@/features/account-profile/client'
|
||||
import { useNodesReadOnly } from '../../hooks/use-workflow'
|
||||
import { getDefaultVisualConfig } from './constants'
|
||||
|
||||
const useConfig = (id: string, payload: ScheduleTriggerNodeType) => {
|
||||
const { nodesReadOnly: readOnly } = useNodesReadOnly()
|
||||
|
||||
const { data: timezone } = useQuery({
|
||||
...userProfileQueryOptions(),
|
||||
select: (data) => data.profile.timezone ?? undefined,
|
||||
})
|
||||
|
||||
const frontendPayload = useMemo(() => {
|
||||
return {
|
||||
...payload,
|
||||
mode: payload.mode || 'visual',
|
||||
frequency: payload.frequency || 'daily',
|
||||
timezone: payload.timezone || timezone || 'UTC',
|
||||
visual_config: {
|
||||
...getDefaultVisualConfig(),
|
||||
...payload.visual_config,
|
||||
},
|
||||
}
|
||||
}, [payload, timezone])
|
||||
|
||||
const { inputs, setInputs } = useNodeCrud<ScheduleTriggerNodeType>(id, frontendPayload)
|
||||
|
||||
// The panel shows the profile timezone, but the backend falls back to UTC when the node has none.
|
||||
// Save the shown timezone so the schedule runs at the time the user sees.
|
||||
useEffect(() => {
|
||||
if (readOnly || payload.timezone || !timezone) return
|
||||
setInputs({ ...inputs, timezone })
|
||||
}, [readOnly, payload.timezone, timezone, inputs, setInputs])
|
||||
|
||||
const handleModeChange = useCallback(
|
||||
(mode: ScheduleMode) => {
|
||||
const newInputs = {
|
||||
...inputs,
|
||||
mode,
|
||||
}
|
||||
setInputs(newInputs)
|
||||
},
|
||||
[inputs, setInputs],
|
||||
)
|
||||
|
||||
const handleFrequencyChange = useCallback(
|
||||
(frequency: ScheduleFrequency) => {
|
||||
const newInputs = {
|
||||
...inputs,
|
||||
frequency,
|
||||
visual_config: {
|
||||
...inputs.visual_config,
|
||||
...(frequency === 'hourly' && {
|
||||
on_minute: inputs.visual_config?.on_minute ?? 0,
|
||||
}),
|
||||
},
|
||||
cron_expression: undefined,
|
||||
}
|
||||
setInputs(newInputs)
|
||||
},
|
||||
[inputs, setInputs],
|
||||
)
|
||||
|
||||
const handleCronExpressionChange = useCallback(
|
||||
(value: string) => {
|
||||
const newInputs = {
|
||||
...inputs,
|
||||
cron_expression: value,
|
||||
frequency: undefined,
|
||||
visual_config: undefined,
|
||||
}
|
||||
setInputs(newInputs)
|
||||
},
|
||||
[inputs, setInputs],
|
||||
)
|
||||
|
||||
const handleWeekdaysChange = useCallback(
|
||||
(weekdays: string[]) => {
|
||||
const newInputs = {
|
||||
...inputs,
|
||||
visual_config: {
|
||||
...inputs.visual_config,
|
||||
weekdays,
|
||||
},
|
||||
cron_expression: undefined,
|
||||
}
|
||||
setInputs(newInputs)
|
||||
},
|
||||
[inputs, setInputs],
|
||||
)
|
||||
|
||||
const handleTimeChange = useCallback(
|
||||
(time: string) => {
|
||||
const newInputs = {
|
||||
...inputs,
|
||||
visual_config: {
|
||||
...inputs.visual_config,
|
||||
time,
|
||||
},
|
||||
cron_expression: undefined,
|
||||
}
|
||||
setInputs(newInputs)
|
||||
},
|
||||
[inputs, setInputs],
|
||||
)
|
||||
|
||||
const handleOnMinuteChange = useCallback(
|
||||
(on_minute: number) => {
|
||||
const newInputs = {
|
||||
...inputs,
|
||||
visual_config: {
|
||||
...inputs.visual_config,
|
||||
on_minute,
|
||||
},
|
||||
cron_expression: undefined,
|
||||
}
|
||||
setInputs(newInputs)
|
||||
},
|
||||
[inputs, setInputs],
|
||||
)
|
||||
|
||||
return {
|
||||
readOnly,
|
||||
inputs,
|
||||
setInputs,
|
||||
handleModeChange,
|
||||
handleFrequencyChange,
|
||||
handleCronExpressionChange,
|
||||
handleWeekdaysChange,
|
||||
handleTimeChange,
|
||||
handleOnMinuteChange,
|
||||
}
|
||||
}
|
||||
|
||||
export default useConfig
|
||||
+109
@@ -0,0 +1,109 @@
|
||||
import type { ScheduleTriggerNodeType } from '../../types'
|
||||
import { BlockEnum } from '../../../../types'
|
||||
import { getFormattedExecutionTimes } from '../execution-time-calculator'
|
||||
|
||||
describe('execution time offset label', () => {
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('shows the offset in effect on each run date across the end of DST', () => {
|
||||
vi.useFakeTimers()
|
||||
vi.setSystemTime(new Date('2026-10-30T12:00:00Z'))
|
||||
|
||||
const data: ScheduleTriggerNodeType = {
|
||||
type: BlockEnum.TriggerSchedule,
|
||||
title: 'schedule',
|
||||
desc: '',
|
||||
mode: 'visual',
|
||||
frequency: 'daily',
|
||||
timezone: 'America/New_York',
|
||||
visual_config: { time: '12:00 AM' },
|
||||
}
|
||||
|
||||
const times = getFormattedExecutionTimes(data, 4)
|
||||
|
||||
expect(times[0]).toContain('October 31, 2026')
|
||||
expect(times[0]).toContain('(UTC-4)')
|
||||
expect(times[1]).toContain('November 1, 2026')
|
||||
expect(times[1]).toContain('(UTC-4)')
|
||||
expect(times[2]).toContain('November 2, 2026')
|
||||
expect(times[2]).toContain('(UTC-5)')
|
||||
})
|
||||
|
||||
it('labels the repeated hour by its real offset when DST ends', () => {
|
||||
vi.useFakeTimers()
|
||||
vi.setSystemTime(new Date('2026-11-01T03:00:00Z'))
|
||||
|
||||
const data: ScheduleTriggerNodeType = {
|
||||
type: BlockEnum.TriggerSchedule,
|
||||
title: 'schedule',
|
||||
desc: '',
|
||||
mode: 'cron',
|
||||
cron_expression: '30 * * * *',
|
||||
timezone: 'America/New_York',
|
||||
}
|
||||
|
||||
const times = getFormattedExecutionTimes(data, 5)
|
||||
|
||||
expect(times[2]).toMatch(/November 1, 2026, 1:30\sAM \(UTC-4\)/)
|
||||
expect(times[3]).toMatch(/November 1, 2026, 1:30\sAM \(UTC-5\)/)
|
||||
})
|
||||
|
||||
it('labels the upcoming repeated hour in visual daily mode', () => {
|
||||
vi.useFakeTimers()
|
||||
vi.setSystemTime(new Date('2026-11-01T06:05:00Z'))
|
||||
|
||||
const data: ScheduleTriggerNodeType = {
|
||||
type: BlockEnum.TriggerSchedule,
|
||||
title: 'schedule',
|
||||
desc: '',
|
||||
mode: 'visual',
|
||||
frequency: 'daily',
|
||||
timezone: 'America/New_York',
|
||||
visual_config: { time: '1:30 AM' },
|
||||
}
|
||||
|
||||
const times = getFormattedExecutionTimes(data, 2)
|
||||
|
||||
expect(times[0]).toMatch(/November 1, 2026, 1:30\sAM \(UTC-5\)/)
|
||||
})
|
||||
|
||||
it('labels the upcoming repeated hour in visual hourly mode', () => {
|
||||
vi.useFakeTimers()
|
||||
vi.setSystemTime(new Date('2026-11-01T06:05:00Z'))
|
||||
|
||||
const data: ScheduleTriggerNodeType = {
|
||||
type: BlockEnum.TriggerSchedule,
|
||||
title: 'schedule',
|
||||
desc: '',
|
||||
mode: 'visual',
|
||||
frequency: 'hourly',
|
||||
timezone: 'America/New_York',
|
||||
visual_config: { on_minute: 30 },
|
||||
}
|
||||
|
||||
const times = getFormattedExecutionTimes(data, 1)
|
||||
|
||||
expect(times[0]).toMatch(/November 1, 2026, 1:30\sAM \(UTC-5\)/)
|
||||
})
|
||||
|
||||
it('labels the first repeated hour in a zone far ahead of UTC', () => {
|
||||
vi.useFakeTimers()
|
||||
vi.setSystemTime(new Date('2026-04-04T08:00:00Z'))
|
||||
|
||||
const data: ScheduleTriggerNodeType = {
|
||||
type: BlockEnum.TriggerSchedule,
|
||||
title: 'schedule',
|
||||
desc: '',
|
||||
mode: 'visual',
|
||||
frequency: 'daily',
|
||||
timezone: 'Pacific/Auckland',
|
||||
visual_config: { time: '2:00 AM' },
|
||||
}
|
||||
|
||||
const times = getFormattedExecutionTimes(data, 1)
|
||||
|
||||
expect(times[0]).toMatch(/April 5, 2026, 2:00\sAM \(UTC\+13\)/)
|
||||
})
|
||||
})
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
import type { ScheduleTriggerNodeType } from '../../types'
|
||||
import { BlockEnum } from '../../../../types'
|
||||
import { getFormattedExecutionTimes, getNextExecutionTime } from '../execution-time-calculator'
|
||||
|
||||
const createHourlyData = (): ScheduleTriggerNodeType => ({
|
||||
type: BlockEnum.TriggerSchedule,
|
||||
title: 'schedule',
|
||||
desc: '',
|
||||
mode: 'visual',
|
||||
frequency: 'hourly',
|
||||
timezone: 'Asia/Seoul',
|
||||
visual_config: { on_minute: 0 },
|
||||
})
|
||||
|
||||
describe('hourly runs across the end of a month', () => {
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('moves to the first day of the next month after midnight', () => {
|
||||
vi.useFakeTimers()
|
||||
vi.setSystemTime(new Date('2026-10-31T13:30:00Z'))
|
||||
|
||||
const times = getFormattedExecutionTimes(createHourlyData(), 3)
|
||||
|
||||
expect(times[0]).toMatch(/October 31, 2026, 11:00\sPM/)
|
||||
expect(times[1]).toMatch(/November 1, 2026, 12:00\sAM/)
|
||||
expect(times[2]).toMatch(/November 1, 2026, 1:00\sAM/)
|
||||
})
|
||||
|
||||
it('moves to January 1 of the next year after New Year midnight', () => {
|
||||
vi.useFakeTimers()
|
||||
vi.setSystemTime(new Date('2026-12-31T14:30:00Z'))
|
||||
|
||||
expect(getNextExecutionTime(createHourlyData())).toMatch(/January 1, 2027, 12:00\sAM/)
|
||||
})
|
||||
})
|
||||
+139
@@ -0,0 +1,139 @@
|
||||
import type { ScheduleTriggerNodeType } from '../../types'
|
||||
import { BlockEnum } from '../../../../types'
|
||||
import { getNextExecutionTime, getNextExecutionTimes } from '../execution-time-calculator'
|
||||
|
||||
const createCronData = (cron_expression: string, timezone = 'UTC'): ScheduleTriggerNodeType => ({
|
||||
type: BlockEnum.TriggerSchedule,
|
||||
title: 'Schedule',
|
||||
desc: '',
|
||||
mode: 'cron',
|
||||
cron_expression,
|
||||
timezone,
|
||||
})
|
||||
|
||||
// The public calculator returns target-zone wall times in the Date's local fields.
|
||||
const wallTime = (date: Date) => [
|
||||
date.getFullYear(),
|
||||
date.getMonth() + 1,
|
||||
date.getDate(),
|
||||
date.getHours(),
|
||||
date.getMinutes(),
|
||||
]
|
||||
|
||||
describe('cron schedule execution preview', () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers()
|
||||
vi.setSystemTime(new Date('2024-01-15T10:00:00Z'))
|
||||
})
|
||||
afterEach(() => vi.useRealTimers())
|
||||
|
||||
it.each([
|
||||
{
|
||||
expression: '*/5 * * * *',
|
||||
expected: [
|
||||
[2024, 1, 15, 10, 5],
|
||||
[2024, 1, 15, 10, 10],
|
||||
[2024, 1, 15, 10, 15],
|
||||
],
|
||||
},
|
||||
{
|
||||
expression: '0 9-17 * * 1-5',
|
||||
expected: [
|
||||
[2024, 1, 15, 11, 0],
|
||||
[2024, 1, 15, 12, 0],
|
||||
[2024, 1, 15, 13, 0],
|
||||
],
|
||||
},
|
||||
{
|
||||
expression: '0 0 1,15 * *',
|
||||
expected: [
|
||||
[2024, 2, 1, 0, 0],
|
||||
[2024, 2, 15, 0, 0],
|
||||
[2024, 3, 1, 0, 0],
|
||||
],
|
||||
},
|
||||
{
|
||||
expression: '30 10 15 JUN,DEC *',
|
||||
expected: [
|
||||
[2024, 6, 15, 10, 30],
|
||||
[2024, 12, 15, 10, 30],
|
||||
[2025, 6, 15, 10, 30],
|
||||
],
|
||||
},
|
||||
{
|
||||
expression: '0 15 * * MON',
|
||||
expected: [
|
||||
[2024, 1, 15, 15, 0],
|
||||
[2024, 1, 22, 15, 0],
|
||||
[2024, 1, 29, 15, 0],
|
||||
],
|
||||
},
|
||||
{
|
||||
expression: '0 15 L * *',
|
||||
expected: [
|
||||
[2024, 1, 31, 15, 0],
|
||||
[2024, 2, 29, 15, 0],
|
||||
[2024, 3, 31, 15, 0],
|
||||
],
|
||||
},
|
||||
])('previews the next three runs for $expression', ({ expression, expected }) => {
|
||||
expect(getNextExecutionTimes(createCronData(expression), 3).map(wallTime)).toEqual(expected)
|
||||
})
|
||||
|
||||
it.each([
|
||||
{ expression: '@daily', expected: [2024, 1, 16, 0, 0] },
|
||||
{ expression: '@weekly', expected: [2024, 1, 21, 0, 0] },
|
||||
{ expression: '@monthly', expected: [2024, 2, 1, 0, 0] },
|
||||
{ expression: '@yearly', expected: [2025, 1, 1, 0, 0] },
|
||||
{ expression: '0 9 ? * 1', expected: [2024, 1, 22, 9, 0] },
|
||||
{ expression: '0 12 * * 7', expected: [2024, 1, 21, 12, 0] },
|
||||
])('supports $expression', ({ expression, expected }) => {
|
||||
expect(getNextExecutionTimes(createCronData(expression), 1).map(wallTime)).toEqual([expected])
|
||||
})
|
||||
|
||||
it.each([
|
||||
{ timezone: 'UTC', expected: [2024, 1, 15, 12, 0] },
|
||||
{ timezone: 'America/New_York', expected: [2024, 1, 15, 12, 0] },
|
||||
{ timezone: 'Asia/Tokyo', expected: [2024, 1, 16, 12, 0] },
|
||||
{ timezone: 'Asia/Kolkata', expected: [2024, 1, 16, 12, 0] },
|
||||
{ timezone: 'Australia/Adelaide', expected: [2024, 1, 16, 12, 0] },
|
||||
{ timezone: 'Pacific/Kiritimati', expected: [2024, 1, 16, 12, 0] },
|
||||
])('chooses the next local noon in $timezone', ({ timezone, expected }) => {
|
||||
expect(getNextExecutionTimes(createCronData('0 12 * * *', timezone), 1).map(wallTime)).toEqual([
|
||||
expected,
|
||||
])
|
||||
})
|
||||
|
||||
it('previews the daylight-saving gap at 3 AM, then returns to 2 AM', () => {
|
||||
vi.setSystemTime(new Date('2024-03-08T10:00:00Z'))
|
||||
expect(
|
||||
getNextExecutionTimes(createCronData('0 2 * * *', 'America/New_York'), 3).map(wallTime),
|
||||
).toEqual([
|
||||
[2024, 3, 9, 2, 0],
|
||||
[2024, 3, 10, 3, 0],
|
||||
[2024, 3, 11, 2, 0],
|
||||
])
|
||||
})
|
||||
|
||||
it.each([
|
||||
'',
|
||||
' ',
|
||||
'60 10 1 * *',
|
||||
'15 25 1 * *',
|
||||
'15 10 32 * *',
|
||||
'15 10 1 13 *',
|
||||
'15 10 1',
|
||||
'15 10 1 * * *',
|
||||
'invalid expression',
|
||||
])('shows no schedule for invalid expression %j', (expression) => {
|
||||
const data = createCronData(expression)
|
||||
expect(getNextExecutionTimes(data)).toEqual([])
|
||||
expect(getNextExecutionTime(data)).toBe('--')
|
||||
})
|
||||
|
||||
it('formats the next run using the selected timezone calendar date', () => {
|
||||
expect(getNextExecutionTime(createCronData('@daily', 'Asia/Tokyo'))).toBe(
|
||||
'January 16, 2024, 12:00 AM',
|
||||
)
|
||||
})
|
||||
})
|
||||
+138
@@ -0,0 +1,138 @@
|
||||
import type { ScheduleTriggerNodeType } from '../../types'
|
||||
import { BlockEnum } from '../../../../types'
|
||||
import {
|
||||
getFormattedExecutionTimes,
|
||||
getNextExecutionTime,
|
||||
getNextExecutionTimes,
|
||||
} from '../execution-time-calculator'
|
||||
|
||||
const weekdays = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat']
|
||||
|
||||
const createWeeklyData = (
|
||||
selectedDays: string[],
|
||||
timezone = 'Asia/Seoul',
|
||||
): ScheduleTriggerNodeType => ({
|
||||
type: BlockEnum.TriggerSchedule,
|
||||
title: 'schedule',
|
||||
desc: '',
|
||||
mode: 'visual',
|
||||
frequency: 'weekly',
|
||||
timezone,
|
||||
visual_config: { time: '9:00 AM', weekdays: selectedDays },
|
||||
})
|
||||
|
||||
const wallTime = (date: Date) => [
|
||||
date.getFullYear(),
|
||||
date.getMonth() + 1,
|
||||
date.getDate(),
|
||||
date.getHours(),
|
||||
date.getMinutes(),
|
||||
]
|
||||
|
||||
describe('weekly schedule execution preview', () => {
|
||||
afterEach(() => vi.useRealTimers())
|
||||
|
||||
it('shows Monday as the next run after Sunday morning', () => {
|
||||
vi.useFakeTimers()
|
||||
vi.setSystemTime(new Date('2026-10-25T01:00:00Z'))
|
||||
|
||||
const data = createWeeklyData(['sun', 'mon'])
|
||||
expect(getNextExecutionTime(data)).toBe('Monday, October 26, 2026, 9:00 AM')
|
||||
expect(getNextExecutionTimes(data, 9).map(wallTime)).toEqual([
|
||||
[2026, 10, 26, 9, 0],
|
||||
[2026, 11, 1, 9, 0],
|
||||
[2026, 11, 2, 9, 0],
|
||||
[2026, 11, 8, 9, 0],
|
||||
[2026, 11, 9, 9, 0],
|
||||
[2026, 11, 15, 9, 0],
|
||||
[2026, 11, 16, 9, 0],
|
||||
[2026, 11, 22, 9, 0],
|
||||
[2026, 11, 23, 9, 0],
|
||||
])
|
||||
expect(getFormattedExecutionTimes(data, 5)[4]).toContain('Monday, November 9, 2026, 9:00 AM')
|
||||
})
|
||||
|
||||
it.each([
|
||||
{ time: '12:00 AM', cron: '0 0' },
|
||||
{ time: '12:00 PM', cron: '0 12' },
|
||||
{ time: '11:59 PM', cron: '59 23' },
|
||||
])('keeps the next five runs in order at $time', ({ time, cron }) => {
|
||||
vi.useFakeTimers()
|
||||
vi.setSystemTime(new Date('2026-10-25T01:00:00Z'))
|
||||
|
||||
const data: ScheduleTriggerNodeType = {
|
||||
...createWeeklyData(['sun', 'mon']),
|
||||
visual_config: { time, weekdays: ['sun', 'mon'] },
|
||||
}
|
||||
const cronData: ScheduleTriggerNodeType = {
|
||||
...data,
|
||||
mode: 'cron',
|
||||
cron_expression: `${cron} * * 0,1`,
|
||||
}
|
||||
|
||||
expect(getNextExecutionTimes(data, 5).map(wallTime)).toEqual(
|
||||
getNextExecutionTimes(cronData, 5).map(wallTime),
|
||||
)
|
||||
})
|
||||
|
||||
it.each([
|
||||
'2026-10-24T23:59:00Z', // Sunday before 9 AM in Seoul
|
||||
'2026-10-25T00:00:00Z', // Sunday at 9 AM in Seoul
|
||||
'2026-10-25T01:00:00Z', // Sunday after 9 AM in Seoul
|
||||
'2026-12-31T15:30:00Z', // New Year in Seoul
|
||||
])('matches the cron schedule for every weekday set at %s', (now) => {
|
||||
vi.useFakeTimers()
|
||||
vi.setSystemTime(new Date(now))
|
||||
|
||||
for (let mask = 1; mask < 1 << weekdays.length; mask++) {
|
||||
const selectedDays = weekdays.filter((_, index) => mask & (1 << index))
|
||||
const cronData: ScheduleTriggerNodeType = {
|
||||
...createWeeklyData(selectedDays),
|
||||
mode: 'cron',
|
||||
cron_expression: `0 9 * * ${selectedDays.map((day) => weekdays.indexOf(day)).join(',')}`,
|
||||
}
|
||||
|
||||
for (const count of [1, 5]) {
|
||||
expect(getNextExecutionTimes(createWeeklyData(selectedDays), count).map(wallTime)).toEqual(
|
||||
getNextExecutionTimes(cronData, count).map(wallTime),
|
||||
)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
it.each([
|
||||
{ timezone: 'America/New_York', now: '2026-10-25T14:00:00Z' }, // DST ends next Sunday
|
||||
{ timezone: 'Pacific/Kiritimati', now: '2026-12-31T11:00:00Z' }, // New Year
|
||||
])('matches cron across a calendar change in $timezone', ({ timezone, now }) => {
|
||||
vi.useFakeTimers()
|
||||
vi.setSystemTime(new Date(now))
|
||||
|
||||
for (let mask = 1; mask < 1 << weekdays.length; mask++) {
|
||||
const selectedDays = weekdays.filter((_, index) => mask & (1 << index))
|
||||
const cronData: ScheduleTriggerNodeType = {
|
||||
...createWeeklyData(selectedDays, timezone),
|
||||
mode: 'cron',
|
||||
cron_expression: `0 9 * * ${selectedDays.map((day) => weekdays.indexOf(day)).join(',')}`,
|
||||
}
|
||||
|
||||
expect(
|
||||
getNextExecutionTimes(createWeeklyData(selectedDays, timezone), 5).map(wallTime),
|
||||
).toEqual(getNextExecutionTimes(cronData, 5).map(wallTime))
|
||||
}
|
||||
})
|
||||
|
||||
it('returns unique runs in date order for repeated and reversed weekdays', () => {
|
||||
vi.useFakeTimers()
|
||||
vi.setSystemTime(new Date('2026-10-25T01:00:00Z'))
|
||||
|
||||
expect(getNextExecutionTimes(createWeeklyData(['mon', 'sun', 'mon']), 3).map(wallTime)).toEqual(
|
||||
[
|
||||
[2026, 10, 26, 9, 0],
|
||||
[2026, 11, 1, 9, 0],
|
||||
[2026, 11, 2, 9, 0],
|
||||
],
|
||||
)
|
||||
expect(getNextExecutionTimes(createWeeklyData([]), 5)).toEqual([])
|
||||
expect(getNextExecutionTimes(createWeeklyData(['sun']), 0)).toEqual([])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,10 @@
|
||||
export function parseClockTime(value: string): string {
|
||||
const match = /^(\d{1,2}):(\d{2})\s*(AM|PM)$/i.exec(value)
|
||||
if (!match) return '00:00'
|
||||
const hour = (Number(match[1]) % 12) + (match[3]!.toUpperCase() === 'PM' ? 12 : 0)
|
||||
return `${String(hour).padStart(2, '0')}:${match[2]}`
|
||||
}
|
||||
export function formatClockTime(value: string): string {
|
||||
const hour = Number(value.slice(0, 2))
|
||||
return `${hour % 12 || 12}:${value.slice(3)} ${hour < 12 ? 'AM' : 'PM'}`
|
||||
}
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
import { CronExpressionParser } from 'cron-parser'
|
||||
|
||||
// Convert a UTC date from cron-parser to user timezone representation
|
||||
// This ensures consistency with other execution time calculations
|
||||
export const convertToUserTimezoneRepresentation = (utcDate: Date, timezone: string): Date => {
|
||||
// Get the time string in the target timezone
|
||||
const userTimeStr = utcDate.toLocaleString('en-CA', {
|
||||
timeZone: timezone,
|
||||
hour12: false,
|
||||
})
|
||||
const [dateStr, timeStr] = userTimeStr.split(', ')
|
||||
const [year, month, day] = dateStr!.split('-').map(Number)
|
||||
const [hour, minute, second] = timeStr!.split(':').map(Number)
|
||||
|
||||
// Create a new Date object representing this time as "local" time
|
||||
// This matches the behavior expected by the execution-time-calculator
|
||||
return new Date(year!, month! - 1, day, hour, minute, second)
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a cron expression and return the next 5 execution instants (real UTC times)
|
||||
*
|
||||
* @param cronExpression - Standard 5-field cron expression (minute hour day month dayOfWeek)
|
||||
* @param timezone - IANA timezone identifier (e.g., 'UTC', 'America/New_York')
|
||||
* @returns Array of Date objects holding the real instant of each run
|
||||
*/
|
||||
export const getCronExecutionInstants = (
|
||||
cronExpression: string,
|
||||
timezone: string = 'UTC',
|
||||
): Date[] => {
|
||||
if (!cronExpression || cronExpression.trim() === '') return []
|
||||
|
||||
const parts = cronExpression.trim().split(/\s+/)
|
||||
|
||||
// Support both 5-field format and predefined expressions
|
||||
if (parts.length !== 5 && !cronExpression.startsWith('@')) return []
|
||||
|
||||
try {
|
||||
const interval = CronExpressionParser.parse(cronExpression, {
|
||||
tz: timezone,
|
||||
})
|
||||
return interval.take(5).map((cronDate) => cronDate.toDate())
|
||||
} catch {
|
||||
// Return empty array if parsing fails
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a cron expression and return the next 5 execution times
|
||||
*
|
||||
* @param cronExpression - Standard 5-field cron expression (minute hour day month dayOfWeek)
|
||||
* @param timezone - IANA timezone identifier (e.g., 'UTC', 'America/New_York')
|
||||
* @returns Array of Date objects representing the next 5 execution times
|
||||
*/
|
||||
export const parseCronExpression = (cronExpression: string, timezone: string = 'UTC'): Date[] =>
|
||||
getCronExecutionInstants(cronExpression, timezone).map((instant) =>
|
||||
convertToUserTimezoneRepresentation(instant, timezone),
|
||||
)
|
||||
|
||||
/**
|
||||
* Validate a cron expression format and syntax
|
||||
*
|
||||
* @param cronExpression - Standard 5-field cron expression to validate
|
||||
* @returns boolean indicating if the cron expression is valid
|
||||
*/
|
||||
export const isValidCronExpression = (cronExpression: string): boolean => {
|
||||
if (!cronExpression || cronExpression.trim() === '') return false
|
||||
|
||||
const parts = cronExpression.trim().split(/\s+/)
|
||||
|
||||
// Support both 5-field format and predefined expressions
|
||||
if (parts.length !== 5 && !cronExpression.startsWith('@')) return false
|
||||
|
||||
try {
|
||||
// Use cron-parser to validate the expression
|
||||
CronExpressionParser.parse(cronExpression)
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
+323
@@ -0,0 +1,323 @@
|
||||
import type { ScheduleTriggerNodeType } from '../types'
|
||||
import { convertTimezoneToOffsetStr, getTimezoneOffsetMinutes } from '@/utils/timezone'
|
||||
import {
|
||||
convertToUserTimezoneRepresentation,
|
||||
getCronExecutionInstants,
|
||||
isValidCronExpression,
|
||||
parseCronExpression,
|
||||
} from './cron-parser'
|
||||
|
||||
const DEFAULT_TIMEZONE = 'UTC'
|
||||
|
||||
const resolveTimezone = (timezone?: string): string => {
|
||||
if (timezone) return timezone
|
||||
|
||||
try {
|
||||
return new Intl.DateTimeFormat().resolvedOptions().timeZone || DEFAULT_TIMEZONE
|
||||
} catch {
|
||||
return DEFAULT_TIMEZONE
|
||||
}
|
||||
}
|
||||
|
||||
// Get current time completely in user timezone, no browser timezone involved
|
||||
const getUserTimezoneCurrentTime = (timezone?: string): Date => {
|
||||
const targetTimezone = resolveTimezone(timezone)
|
||||
const now = new Date()
|
||||
const userTimeStr = now.toLocaleString('en-CA', {
|
||||
timeZone: targetTimezone,
|
||||
hour12: false,
|
||||
})
|
||||
const [dateStr, timeStr] = userTimeStr.split(', ')
|
||||
const [year, month, day] = dateStr!.split('-').map(Number)
|
||||
const [hour, minute, second] = timeStr!.split(':').map(Number)
|
||||
return new Date(year!, month! - 1, day, hour, minute, second)
|
||||
}
|
||||
|
||||
// The Date objects here hold the wall time of the target timezone in local fields.
|
||||
// Turn that wall time back into the real instant so the offset label follows DST.
|
||||
// When DST ends, one wall time happens twice. Pick the first one that is not in the past.
|
||||
const getWallTimeInstant = (date: Date, timezone: string): Date => {
|
||||
const wallAsUtc = Date.UTC(
|
||||
date.getFullYear(),
|
||||
date.getMonth(),
|
||||
date.getDate(),
|
||||
date.getHours(),
|
||||
date.getMinutes(),
|
||||
date.getSeconds(),
|
||||
)
|
||||
const offsetAt = (time: number) => getTimezoneOffsetMinutes(timezone, new Date(time)) ?? 0
|
||||
// Offsets a day before and after cover both sides of any DST change near this wall time.
|
||||
const offsetsNearby = [offsetAt(wallAsUtc - 24 * 3_600_000), offsetAt(wallAsUtc + 24 * 3_600_000)]
|
||||
const candidates = [...new Set(offsetsNearby)]
|
||||
.map((offset) => wallAsUtc - offset * 60_000)
|
||||
.filter((time) => offsetAt(time) === (wallAsUtc - time) / 60_000)
|
||||
.sort((a, b) => a - b)
|
||||
|
||||
// No candidate means the wall time falls in the DST gap. The run happens after
|
||||
// the clocks move forward, so the label shows the new offset.
|
||||
if (candidates.length === 0) return new Date(wallAsUtc - offsetsNearby[0]! * 60_000)
|
||||
|
||||
const now = Date.now()
|
||||
return new Date(candidates.find((time) => time >= now) ?? candidates[0]!)
|
||||
}
|
||||
|
||||
// Format date that is already in user timezone, no timezone conversion
|
||||
const formatUserTimezoneDate = (
|
||||
date: Date,
|
||||
timezone: string,
|
||||
includeWeekday: boolean = true,
|
||||
includeTimezone: boolean = true,
|
||||
): string => {
|
||||
const dateOptions: Intl.DateTimeFormatOptions = {
|
||||
year: 'numeric',
|
||||
month: 'long',
|
||||
day: 'numeric',
|
||||
}
|
||||
|
||||
if (includeWeekday) dateOptions.weekday = 'long' // Changed from 'short' to 'long' for full weekday name
|
||||
|
||||
const timeOptions: Intl.DateTimeFormatOptions = {
|
||||
hour: 'numeric',
|
||||
minute: '2-digit',
|
||||
hour12: true,
|
||||
}
|
||||
|
||||
const dateStr = date.toLocaleDateString('en-US', dateOptions)
|
||||
const timeStr = date.toLocaleTimeString('en-US', timeOptions)
|
||||
|
||||
if (includeTimezone) {
|
||||
const timezoneOffset = convertTimezoneToOffsetStr(timezone, getWallTimeInstant(date, timezone))
|
||||
return `${dateStr}, ${timeStr} (${timezoneOffset})`
|
||||
}
|
||||
|
||||
return `${dateStr}, ${timeStr}`
|
||||
}
|
||||
|
||||
export const getNextExecutionTimes = (data: ScheduleTriggerNodeType, count: number = 5): Date[] => {
|
||||
const timezone = resolveTimezone(data.timezone)
|
||||
|
||||
if (data.mode === 'cron') {
|
||||
if (!data.cron_expression || !isValidCronExpression(data.cron_expression)) return []
|
||||
return parseCronExpression(data.cron_expression, timezone).slice(0, count)
|
||||
}
|
||||
|
||||
const times: Date[] = []
|
||||
const defaultTime = data.visual_config?.time || '12:00 AM'
|
||||
|
||||
// Get "today" in user's timezone for display purposes
|
||||
const now = new Date()
|
||||
const userTodayStr = now.toLocaleDateString('en-CA', { timeZone: timezone })
|
||||
const [year, month, day] = userTodayStr.split('-').map(Number)
|
||||
const userToday = new Date(year!, month! - 1, day, 0, 0, 0, 0)
|
||||
|
||||
if (data.frequency === 'hourly') {
|
||||
const onMinute = data.visual_config?.on_minute ?? 0
|
||||
|
||||
// Get current time completely in user timezone
|
||||
const userCurrentTime = getUserTimezoneCurrentTime(timezone)
|
||||
|
||||
let hour = userCurrentTime.getHours()
|
||||
if (userCurrentTime.getMinutes() >= onMinute) hour += 1 // Start from next hour if current minute has passed
|
||||
|
||||
for (let i = 0; i < count; i++) {
|
||||
const execution = new Date(userToday)
|
||||
// setHours rolls past midnight into the next day, month and year on its own
|
||||
execution.setHours(hour + i, onMinute, 0, 0)
|
||||
times.push(execution)
|
||||
}
|
||||
} else if (data.frequency === 'daily') {
|
||||
const [time, period] = defaultTime.split(' ')
|
||||
const [hour, minute] = time!.split(':')
|
||||
let displayHour = Number.parseInt(hour!)
|
||||
if (period === 'PM' && displayHour !== 12) displayHour += 12
|
||||
if (period === 'AM' && displayHour === 12) displayHour = 0
|
||||
|
||||
// Check if today's configured time has already passed
|
||||
const todayExecution = new Date(userToday)
|
||||
todayExecution.setHours(displayHour, Number.parseInt(minute!), 0, 0)
|
||||
|
||||
const userCurrentTime = getUserTimezoneCurrentTime(timezone)
|
||||
|
||||
const startOffset = todayExecution <= userCurrentTime ? 1 : 0
|
||||
|
||||
for (let i = 0; i < count; i++) {
|
||||
const execution = new Date(userToday)
|
||||
execution.setDate(userToday.getDate() + startOffset + i)
|
||||
execution.setHours(displayHour, Number.parseInt(minute!), 0, 0)
|
||||
times.push(execution)
|
||||
}
|
||||
} else if (data.frequency === 'weekly') {
|
||||
const dayMap = { sun: 0, mon: 1, tue: 2, wed: 3, thu: 4, fri: 5, sat: 6 }
|
||||
const selectedDays = new Set(
|
||||
(data.visual_config?.weekdays || ['sun'])
|
||||
.map((day) => dayMap[day as keyof typeof dayMap])
|
||||
.filter((day): day is number => day !== undefined),
|
||||
)
|
||||
|
||||
if (selectedDays.size === 0) return times
|
||||
|
||||
const [time, period] = defaultTime.split(' ')
|
||||
const [hour, minute] = time!.split(':')
|
||||
let displayHour = Number.parseInt(hour!)
|
||||
if (period === 'PM' && displayHour !== 12) displayHour += 12
|
||||
if (period === 'AM' && displayHour === 12) displayHour = 0
|
||||
|
||||
// Get current time completely in user timezone
|
||||
const userCurrentTime = getUserTimezoneCurrentTime(timezone)
|
||||
|
||||
let dayOffset = 0
|
||||
while (times.length < count) {
|
||||
const execution = new Date(userToday)
|
||||
execution.setDate(userToday.getDate() + dayOffset)
|
||||
execution.setHours(displayHour, Number.parseInt(minute!), 0, 0)
|
||||
|
||||
if (selectedDays.has(execution.getDay()) && execution > userCurrentTime) times.push(execution)
|
||||
|
||||
dayOffset++
|
||||
}
|
||||
} else if (data.frequency === 'monthly') {
|
||||
const getSelectedDays = (): (number | 'last')[] => {
|
||||
if (data.visual_config?.monthly_days && data.visual_config.monthly_days.length > 0)
|
||||
return data.visual_config.monthly_days
|
||||
|
||||
return [1]
|
||||
}
|
||||
|
||||
const selectedDays = [...new Set(getSelectedDays())]
|
||||
const [time, period] = defaultTime.split(' ')
|
||||
const [hour, minute] = time!.split(':')
|
||||
let displayHour = Number.parseInt(hour!)
|
||||
if (period === 'PM' && displayHour !== 12) displayHour += 12
|
||||
if (period === 'AM' && displayHour === 12) displayHour = 0
|
||||
|
||||
// Get current time completely in user timezone
|
||||
const userCurrentTime = getUserTimezoneCurrentTime(timezone)
|
||||
|
||||
let executionCount = 0
|
||||
let monthOffset = 0
|
||||
|
||||
while (executionCount < count) {
|
||||
const targetMonth = new Date(userToday.getFullYear(), userToday.getMonth() + monthOffset, 1)
|
||||
const daysInMonth = new Date(
|
||||
targetMonth.getFullYear(),
|
||||
targetMonth.getMonth() + 1,
|
||||
0,
|
||||
).getDate()
|
||||
|
||||
const monthlyExecutions: Date[] = []
|
||||
const processedDays = new Set<number>()
|
||||
|
||||
for (const selectedDay of selectedDays) {
|
||||
let targetDay: number
|
||||
|
||||
if (selectedDay === 'last') {
|
||||
targetDay = daysInMonth
|
||||
} else {
|
||||
const dayNumber = selectedDay
|
||||
if (dayNumber > daysInMonth) continue
|
||||
|
||||
targetDay = dayNumber
|
||||
}
|
||||
|
||||
if (processedDays.has(targetDay)) continue
|
||||
|
||||
processedDays.add(targetDay)
|
||||
|
||||
const execution = new Date(
|
||||
targetMonth.getFullYear(),
|
||||
targetMonth.getMonth(),
|
||||
targetDay,
|
||||
displayHour,
|
||||
Number.parseInt(minute!),
|
||||
0,
|
||||
0,
|
||||
)
|
||||
|
||||
// Only add if execution time is in the future
|
||||
if (execution > userCurrentTime) monthlyExecutions.push(execution)
|
||||
}
|
||||
|
||||
monthlyExecutions.sort((a, b) => a.getTime() - b.getTime())
|
||||
|
||||
for (const execution of monthlyExecutions) {
|
||||
if (executionCount >= count) break
|
||||
times.push(execution)
|
||||
executionCount++
|
||||
}
|
||||
|
||||
monthOffset++
|
||||
}
|
||||
} else {
|
||||
for (let i = 0; i < count; i++) {
|
||||
const execution = new Date(userToday)
|
||||
execution.setDate(userToday.getDate() + i)
|
||||
times.push(execution)
|
||||
}
|
||||
}
|
||||
|
||||
return times
|
||||
}
|
||||
|
||||
const formatExecutionTime = (
|
||||
date: Date,
|
||||
timezone: string | undefined,
|
||||
includeWeekday: boolean = true,
|
||||
includeTimezone: boolean = true,
|
||||
): string => {
|
||||
const resolvedTimezone = resolveTimezone(timezone)
|
||||
return formatUserTimezoneDate(date, resolvedTimezone, includeWeekday, includeTimezone)
|
||||
}
|
||||
|
||||
export const getFormattedExecutionTimes = (
|
||||
data: ScheduleTriggerNodeType,
|
||||
count: number = 5,
|
||||
): string[] => {
|
||||
const timezone = resolveTimezone(data.timezone)
|
||||
// Cron runs can repeat a wall time when DST ends, so label each run from its real instant.
|
||||
if (data.mode === 'cron') {
|
||||
if (!data.cron_expression || !isValidCronExpression(data.cron_expression)) return []
|
||||
return getCronExecutionInstants(data.cron_expression, timezone)
|
||||
.slice(0, count)
|
||||
.map((instant) => {
|
||||
const wallTime = convertToUserTimezoneRepresentation(instant, timezone)
|
||||
const label = formatUserTimezoneDate(wallTime, timezone, false, false)
|
||||
return `${label} (${convertTimezoneToOffsetStr(timezone, instant)})`
|
||||
})
|
||||
}
|
||||
const times = getNextExecutionTimes(data, count)
|
||||
|
||||
return times.map((date) => {
|
||||
const includeWeekday = data.mode === 'visual' && data.frequency === 'weekly'
|
||||
return formatExecutionTime(date, timezone, includeWeekday, true) // Panel shows timezone
|
||||
})
|
||||
}
|
||||
|
||||
export const getNextExecutionTime = (data: ScheduleTriggerNodeType): string => {
|
||||
const timezone = resolveTimezone(data.timezone)
|
||||
|
||||
// Return placeholder for cron mode with empty or invalid expression
|
||||
if (data.mode === 'cron') {
|
||||
if (!data.cron_expression || !isValidCronExpression(data.cron_expression)) return '--'
|
||||
}
|
||||
|
||||
// Get Date objects (not formatted strings)
|
||||
const times = getNextExecutionTimes(data, 1)
|
||||
if (times.length === 0) {
|
||||
const userCurrentTime = getUserTimezoneCurrentTime(timezone)
|
||||
const fallbackDate = new Date(
|
||||
userCurrentTime.getFullYear(),
|
||||
userCurrentTime.getMonth(),
|
||||
userCurrentTime.getDate(),
|
||||
12,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
)
|
||||
const includeWeekday = data.mode === 'visual' && data.frequency === 'weekly'
|
||||
return formatExecutionTime(fallbackDate, timezone, includeWeekday, false) // Node doesn't show timezone
|
||||
}
|
||||
|
||||
// Format the first execution time without timezone for node display
|
||||
const includeWeekday = data.mode === 'visual' && data.frequency === 'weekly'
|
||||
return formatExecutionTime(times[0]!, timezone, includeWeekday, false) // Node doesn't show timezone
|
||||
}
|
||||
Reference in new issue
Block a user