n8n/packages/nodes-base/nodes/Schedule/GenericFunctions.ts
agobrech 78bbe2ba27
fix(Schedule Trigger Node): Change scheduler behaviour for intervals days and hours (#5133)
* 🐛Fix scheduler for intervals days and week

* ♻️ Simplify and move recurrency rules outside trigger node

* Remove async and promise from recurency rule

* Update correctly the Static data when using recurrency Rule

* Fix logic when recurrency is activated

* 🎨 Remove useless staticData fix(passed by reference)

* 🐛 remove duplicted hour cronJob leading to 2 executions

* More fixes, handles multiple execution

* 🐛 fixing dayOfYear recurency check

* 🐛 fix recurency check for hours/days should not equal lastExecution

* Add month interval to the scheduler

* Fix flawed logic for comparing interval

* 🚨 Fix lint issue type

---------

Co-authored-by: Marcus <marcus@n8n.io>
2023-02-01 22:53:05 +01:00

58 lines
1.9 KiB
TypeScript

import type { IRecurencyRule } from './SchedulerInterface';
import moment from 'moment';
export function recurencyCheck(
recurrency: IRecurencyRule,
recurrencyRules: number[],
timezone: string,
): boolean {
const recurrencyRuleIndex = recurrency.index;
const intervalSize = recurrency.intervalSize;
const typeInterval = recurrency.typeInterval;
const lastExecution =
recurrencyRuleIndex !== undefined ? recurrencyRules[recurrencyRuleIndex] : undefined;
if (
intervalSize &&
recurrencyRuleIndex !== undefined &&
(typeInterval === 'weeks' || typeInterval === 'undefined')
) {
if (
lastExecution === undefined || // First time executing this rule
moment.tz(timezone).week() === (intervalSize + lastExecution) % 52 || // not first time, but minimum interval has passed
moment.tz(timezone).week() === lastExecution // Trigger on multiple days in the same week
) {
recurrencyRules[recurrencyRuleIndex] = moment.tz(timezone).week();
return true;
}
} else if (intervalSize && recurrencyRuleIndex !== undefined && typeInterval === 'days') {
if (
lastExecution === undefined ||
moment.tz(timezone).dayOfYear() === (intervalSize + lastExecution) % 365
) {
recurrencyRules[recurrencyRuleIndex] = moment.tz(timezone).dayOfYear();
return true;
}
} else if (intervalSize && recurrencyRuleIndex !== undefined && typeInterval === 'hours') {
if (
lastExecution === undefined ||
moment.tz(timezone).hour() === (intervalSize + lastExecution) % 24
) {
recurrencyRules[recurrencyRuleIndex] = moment.tz(timezone).hour();
return true;
}
} else if (intervalSize && recurrencyRuleIndex !== undefined && typeInterval === 'months') {
if (
lastExecution === undefined ||
moment.tz(timezone).month() === (intervalSize + lastExecution) % 12
) {
recurrencyRules[recurrencyRuleIndex] = moment.tz(timezone).month();
return true;
}
} else {
return true;
}
return false;
}