diff --git a/client/src/components/ChoreScheduleBoard.jsx b/client/src/components/ChoreScheduleBoard.jsx
index f51d80df..ed877ec4 100644
--- a/client/src/components/ChoreScheduleBoard.jsx
+++ b/client/src/components/ChoreScheduleBoard.jsx
@@ -43,6 +43,7 @@ import { API_BASE_URL } from '../utils/apiConfig.js';
import { adminHeadingRowSx, adminHeadingTextSx } from './AdminRows.jsx';
import useIsMobile from '../hooks/useIsMobile.js';
import { getTodayDateString } from '../utils/choreHelpers.js';
+import { rhythmAnchor, rhythmOffset } from '../utils/choreDays.js';
import { getServerTimezoneSync } from '../utils/timezone.js';
import { parseVacationModeSetting } from '../utils/interfaceSettings.js';
import {
@@ -61,6 +62,7 @@ import { calendarRoutinesFor } from '../utils/routineSchedules.js';
import { SearchMark } from './ChoresPageBar.jsx';
import ScheduleWizard, { WIZARD_START } from './ScheduleWizard.jsx';
import SchedulePicker, {
+ WeekRhythmFields,
AddModeToggle,
CustomPanel,
DAY_ORDER,
@@ -86,6 +88,8 @@ const BONUS = 'bonus';
const COPIED_FIELDS = [
'crontab', 'duration', 'interval', 'due_date', 'due_time', 'expire_minutes', 'sound_enabled',
'sound', 'reminder_interval_minutes', 'transferable', 'can_snooze', 'visible',
+ // Every few weeks (issue #401), on the same weeks.
+ 'week_interval', 'week_anchor',
];
// How each calendar entry looks: a mark, and a tint that reads in both themes.
@@ -335,6 +339,9 @@ export default function ChoreScheduleBoard({
setEditDialog({
group,
days: tm.days || [],
+ // Every few weeks (issue #401): kept unless changed here.
+ every: tm.every || 1,
+ offset: tm.every ? rhythmOffset(today, tm.anchor, tm.every) : 0,
n: tm.n || 2,
dom: tm.dom || '1',
date: tm.dueDate || '',
@@ -348,7 +355,9 @@ export default function ChoreScheduleBoard({
const editedTiming = (d) => {
if (!d) return null;
switch (d.group.timing.kind) {
- case 'week': return d.days.length ? weekTiming(d.days) : null;
+ case 'week': return d.days.length
+ ? weekTiming(d.days, d.every || 1, (d.every || 1) > 1 ? rhythmAnchor(today, d.offset || 0) : null)
+ : null;
case 'everyN': return Number(d.n) >= 2 ? everyNTiming(Number(d.n)) : null;
case 'monthly': return /^\s*\d{1,2}(\s*,\s*\d{1,2})*\s*$/.test(d.dom) && d.dom.split(',').every((x) => Number(x) >= 1 && Number(x) <= 31)
? monthlyTiming(d.dom.replace(/\s+/g, '')) : null;
@@ -866,6 +875,7 @@ export default function ChoreScheduleBoard({
{DAY_ORDER.map((x) => {shortDays[x]})}
)}
+ {kind === 'week' && set({ every, offset })} />}
{kind === 'everyN' && (
set({ n: e.target.value })} slotProps={{ htmlInput: { min: 2, max: 31 } }} sx={{ maxWidth: 200 }} />
)}
diff --git a/client/src/components/ChoreSchedulesTab.jsx b/client/src/components/ChoreSchedulesTab.jsx
index ba3f28f0..966071a0 100644
--- a/client/src/components/ChoreSchedulesTab.jsx
+++ b/client/src/components/ChoreSchedulesTab.jsx
@@ -41,6 +41,7 @@ import {
import axios from 'axios';
import { API_BASE_URL } from '../utils/apiConfig.js';
import { CronExpressionParser } from 'cron-parser';
+import { onWeekRhythm } from '../utils/choreDays.js';
import { getServerTimezoneSync } from '../utils/timezone.js';
import SoundPicker from './SoundPicker.jsx';
import { useTranslation } from 'react-i18next';
@@ -85,19 +86,28 @@ const CRONTAB_PRESETS = [
// column can sort on the instant rather than on the formatted string. Null
// means there is no next occurrence: a one-time task, or an expression that
// does not parse.
-function nextOccurrenceAt(crontab) {
+// `schedule` is { crontab, week_interval, week_anchor }: one repeating every
+// few weeks (issue #401) skips the weeks that aren't its own.
+function nextOccurrenceAt(schedule) {
+ const crontab = schedule?.crontab;
if (!crontab) return null;
try {
const tz = getServerTimezoneSync();
- return CronExpressionParser.parse(crontab, { tz }).next().toDate();
+ const it = CronExpressionParser.parse(crontab, { tz });
+ const keyOf = (date) => new Intl.DateTimeFormat('en-CA', { timeZone: tz || undefined, year: 'numeric', month: '2-digit', day: '2-digit' }).format(date);
+ for (let i = 0; i < 200; i += 1) {
+ const next = it.next().toDate();
+ if (onWeekRhythm(schedule, keyOf(next))) return next;
+ }
+ return null;
} catch {
return null;
}
}
-function getNextOccurrence(crontab) {
- if (!crontab) return 'One-time';
- const next = nextOccurrenceAt(crontab);
+function getNextOccurrence(schedule) {
+ if (!schedule?.crontab) return 'One-time';
+ const next = nextOccurrenceAt(schedule);
if (!next) return 'Invalid expression';
const tz = getServerTimezoneSync();
return next.toLocaleDateString(undefined, { weekday: 'short', month: 'short', day: 'numeric', timeZone: tz });
@@ -644,7 +654,7 @@ export default function ChoreSchedulesTab({ setSaveMessage, section, onSection,
const scheduleSortKeys = {
chore: s => String(s?.title ?? ''),
assignedTo: s => getUserName(s?.user_id),
- nextOccurrence: s => nextOccurrenceAt(s?.crontab)?.getTime() ?? null,
+ nextOccurrence: s => nextOccurrenceAt(s)?.getTime() ?? null,
clams: s => Number(s?.clam_value ?? 0),
};
@@ -718,7 +728,14 @@ export default function ChoreSchedulesTab({ setSaveMessage, section, onSection,
};
const currentCrontab = computeCrontab(scheduleForm);
- const nextOccurrence = getNextOccurrence(currentCrontab);
+ // The schedule being edited keeps its rhythm while its days stay days of
+ // the week (the server drops it otherwise, issue #401).
+ const nextOccurrence = getNextOccurrence({
+ crontab: currentCrontab,
+ ...(editingSchedule && /^\S+\s+\S+\s+\*\s+\*\s+\S+$/.test(String(currentCrontab || '').trim())
+ ? { week_interval: editingSchedule.week_interval, week_anchor: editingSchedule.week_anchor }
+ : {}),
+ });
const isOnceCompletedMissingInterval = !scheduleForm.isOneTime
&& scheduleForm.duration === 'once-completed'
&& !(Number.isInteger(Number.parseInt(scheduleForm.sleepCount, 10)) && Number.parseInt(scheduleForm.sleepCount, 10) > 0);
@@ -995,7 +1012,7 @@ export default function ChoreSchedulesTab({ setSaveMessage, section, onSection,
{s.duration === 'any-day'
? t('chores:schedules.anyDayNext')
- : `${t('chores:schedules.nextOccurrence')}: ${getNextOccurrence(s.crontab)}`}
+ : `${t('chores:schedules.nextOccurrence')}: ${getNextOccurrence(s)}`}
>
)}
diff --git a/client/src/components/SchedulePicker.jsx b/client/src/components/SchedulePicker.jsx
index c237fc04..c9ef5dd1 100644
--- a/client/src/components/SchedulePicker.jsx
+++ b/client/src/components/SchedulePicker.jsx
@@ -12,6 +12,8 @@ import {
} from '@mui/material';
import { useTranslation } from 'react-i18next';
import { getWeekdayLabels, getWeekdayOptions } from '../utils/dateUtils.js';
+import { getTodayDateString } from '../utils/choreHelpers.js';
+import { addDays, rhythmAnchor, onWeekRhythm } from '../utils/choreDays.js';
import {
COMMON_TIMINGS,
afterTiming,
@@ -84,6 +86,24 @@ export function useTimingLabel() {
switch (timing.kind) {
case 'week': {
const d = timing.days;
+ // Every few weeks (issue #401): which days, and the next one, so
+ // two groups on opposite weeks read apart.
+ if (timing.every) {
+ const days = d.length === 7 ? t('chores:board.timing.allWeekDays')
+ : d.length === 1 ? longDays[d[0]]
+ : DAY_ORDER.filter((x) => d.includes(x)).map((x) => shortDays[x]).join(' · ');
+ const today = getTodayDateString();
+ let next = null;
+ for (let i = 0; i < timing.every * 7 && !next; i += 1) {
+ const key = addDays(today, i);
+ const weekday = new Date(`${key}T12:00:00Z`).getUTCDay();
+ if (d.includes(weekday) && onWeekRhythm({ week_interval: timing.every, week_anchor: timing.anchor }, key)) next = key;
+ }
+ const date = next ? dateLabel(next) : '';
+ return timing.every === 2
+ ? t('chores:board.timing.everyOtherWeek', { days, date })
+ : t('chores:board.timing.everyNWeeks', { days, date, count: timing.every });
+ }
if (d.length === 7) return t('chores:board.timing.everyDay');
if (d.join() === '1,2,3,4,5') return t('chores:board.timing.weekdays');
if (d.join() === '0,6') return t('chores:board.timing.weekends');
@@ -131,6 +151,56 @@ export function AddModeToggle({ value, onChange, sx }) {
);
}
+/**
+ * Every week, or every 2, 3 or 4 weeks starting this week, next week, …
+ * (issue #401). `every` is 1-4 and `offset` the starting week, 0 for this
+ * one; the anchor is that week's Sunday (utils/choreDays.js rhythmAnchor).
+ */
+export function WeekRhythmFields({ every = 1, offset = 0, onChange }) {
+ const { t } = useTranslation(['chores']);
+ const today = getTodayDateString();
+ const startLabel = (k) => (k === 0 ? t('chores:board.rhythm.thisWeek') : k === 1 ? t('chores:board.rhythm.nextWeek') : t('chores:board.rhythm.inWeeks', { count: k }));
+ return (
+
+ {t('chores:board.rhythm.every')}
+ value && onChange({ every: value, offset: value > 1 ? Math.min(offset, value - 1) : 0 })}
+ aria-labelledby="rhythm-every-label"
+ sx={{ flexWrap: 'wrap' }}
+ >
+ {[1, 2, 3, 4].map((n) => (
+
+ {n === 1 ? t('chores:board.rhythm.week') : t('chores:board.unit_w', { count: n })}
+
+ ))}
+
+ {every > 1 && (
+ <>
+ {t('chores:board.rhythm.starting')}
+ value !== null && onChange({ every, offset: value })}
+ aria-labelledby="rhythm-start-label"
+ sx={{ flexWrap: 'wrap' }}
+ >
+ {Array.from({ length: every }, (_, k) => (
+
+ {startLabel(k)}
+ {t('chores:board.rhythm.weekOf', { date: dateLabel(rhythmAnchor(today, k)) })}
+
+ ))}
+
+ >
+ )}
+
+ );
+}
+
/** Every day / Weekdays / Weekends buttons that fill the day toggles. */
export function QuickDays({ onPick }) {
const { t } = useTranslation(['chores']);
diff --git a/client/src/components/ScheduleWizard.jsx b/client/src/components/ScheduleWizard.jsx
index fc8e70b2..4e2ccf66 100644
--- a/client/src/components/ScheduleWizard.jsx
+++ b/client/src/components/ScheduleWizard.jsx
@@ -11,6 +11,9 @@ import {
Typography,
} from '@mui/material';
import { ArrowBack, ArrowForward } from '@mui/icons-material';
+import { getTodayDateString } from '../utils/choreHelpers.js';
+import { rhythmAnchor } from '../utils/choreDays.js';
+import { WeekRhythmFields } from './SchedulePicker.jsx';
import { useTranslation } from 'react-i18next';
import {
ANY_DAY_PERIODS,
@@ -34,6 +37,8 @@ import {
export const WIZARD_START = {
step: 'how', how: null, days: [], n: 2, period: '1w', dom: [1], count: 2, unit: 'w', date: '', keep: false,
+ // Every few weeks (issue #401): every 1-4 weeks, starting `offset` weeks on.
+ every: 1, offset: 0,
};
const HOWS = ['days', 'anyDay', 'everyN', 'monthly', 'after', 'once'];
@@ -58,7 +63,9 @@ const wholeIn = (value, min, max) => {
// The timing the answers so far make, or null while incomplete.
export function wizardTiming(w) {
switch (w.how) {
- case 'days': return w.days.length ? weekTiming(w.days) : null;
+ case 'days': return w.days.length
+ ? weekTiming(w.days, w.every || 1, (w.every || 1) > 1 ? rhythmAnchor(getTodayDateString(), w.offset || 0) : null)
+ : null;
case 'everyN': {
const n = wholeIn(w.n, 2, 60);
return n === null ? null : everyNTiming(n);
@@ -166,6 +173,7 @@ export default function ScheduleWizard({ value: w, onChange, onDone, timingLabel
>
{DAY_ORDER.map((d) => {shortDays[d]})}
+ set({ every, offset })} />
>
)}
diff --git a/client/src/i18n/locales/en/chores.json b/client/src/i18n/locales/en/chores.json
index c6b7a1c2..21f15828 100644
--- a/client/src/i18n/locales/en/chores.json
+++ b/client/src/i18n/locales/en/chores.json
@@ -597,7 +597,21 @@
"custom": "Custom ({{expr}})",
"yearly": "Every year · {{date}}",
"everyNMonths_one": "Every month · {{dates}}",
- "everyNMonths_other": "Every {{count}} months · {{dates}}"
+ "everyNMonths_other": "Every {{count}} months · {{dates}}",
+ "everyOtherWeek": "Every other week: {{days}} (next {{date}})",
+ "everyNWeeks_one": "Every {{count}} weeks: {{days}} (next {{date}})",
+ "everyNWeeks_other": "Every {{count}} weeks: {{days}} (next {{date}})",
+ "allWeekDays": "every day"
+ },
+ "rhythm": {
+ "every": "Every",
+ "week": "Week",
+ "starting": "Starting",
+ "thisWeek": "This week",
+ "nextWeek": "Next week",
+ "inWeeks_one": "In {{count}} week",
+ "inWeeks_other": "In {{count}} weeks",
+ "weekOf": "week of {{date}}"
}
},
"wizard": {
diff --git a/client/src/i18n/locales/es/chores.json b/client/src/i18n/locales/es/chores.json
index e4d2c8dd..dda963c5 100644
--- a/client/src/i18n/locales/es/chores.json
+++ b/client/src/i18n/locales/es/chores.json
@@ -597,7 +597,21 @@
"custom": "Personalizado ({{expr}})",
"yearly": "Cada año · {{date}}",
"everyNMonths_one": "Cada mes · {{dates}}",
- "everyNMonths_other": "Cada {{count}} meses · {{dates}}"
+ "everyNMonths_other": "Cada {{count}} meses · {{dates}}",
+ "everyOtherWeek": "Cada dos semanas: {{days}} (siguiente: {{date}})",
+ "everyNWeeks_one": "Cada {{count}} semanas: {{days}} (siguiente: {{date}})",
+ "everyNWeeks_other": "Cada {{count}} semanas: {{days}} (siguiente: {{date}})",
+ "allWeekDays": "todos los días"
+ },
+ "rhythm": {
+ "every": "Cada",
+ "week": "Semana",
+ "starting": "Empieza",
+ "thisWeek": "Esta semana",
+ "nextWeek": "La semana que viene",
+ "inWeeks_one": "Dentro de {{count}} semana",
+ "inWeeks_other": "Dentro de {{count}} semanas",
+ "weekOf": "semana del {{date}}"
}
},
"wizard": {
diff --git a/client/src/utils/choreDays.js b/client/src/utils/choreDays.js
index ee215758..b0e9d7ec 100644
--- a/client/src/utils/choreDays.js
+++ b/client/src/utils/choreDays.js
@@ -50,6 +50,54 @@ export function cronFiresOn(crontab, dateStr) {
return domMatch || dowMatch;
}
+// Every N weeks on set weekdays (issue #401), as the server has it
+// (server/utils/weekRhythm.js): a schedule with week_interval 2, 3 or 4
+// counts only in the weeks that are a whole number of intervals from the
+// week of week_anchor. Weeks run Sunday to Saturday.
+export const WEEK_INTERVALS = [2, 3, 4];
+const dayMs = (key) => { const [y, m, d] = String(key).slice(0, 10).split('-').map(Number); return Date.UTC(y, m - 1, d); };
+
+/** The Sunday ('YYYY-MM-DD') of the week `dateStr` is in. */
+export function weekStartKey(dateStr) {
+ return addDays(String(dateStr).slice(0, 10), -new Date(dayMs(dateStr)).getUTCDay());
+}
+
+/** Whole weeks from `fromKey`'s week to `toKey`'s; negative before it. */
+export function weeksBetweenKeys(fromKey, toKey) {
+ return Math.round((dayMs(weekStartKey(toKey)) - dayMs(weekStartKey(fromKey))) / (7 * 86400000));
+}
+
+const isRhythm = (every, anchor) => WEEK_INTERVALS.includes(Number(every)) && /^\d{4}-\d{2}-\d{2}$/.test(String(anchor || ''));
+
+/** Whether `dateStr`'s week counts for a schedule (true without a rhythm). */
+export function onWeekRhythm(schedule, dateStr) {
+ if (!isRhythm(schedule?.week_interval, schedule?.week_anchor)) return true;
+ const every = Number(schedule.week_interval);
+ const weeks = weeksBetweenKeys(schedule.week_anchor, dateStr);
+ return ((weeks % every) + every) % every === 0;
+}
+
+/**
+ * Whether a schedule is due on `dateStr`: its crontab fires that day, and
+ * that week is one of its weeks. The server's scheduleFiresOnDate, which the
+ * daily bonus and the misses use; every "is it due" here asks this.
+ */
+export function scheduleFiresOn(schedule, dateStr) {
+ return cronFiresOn(schedule.crontab, dateStr) && onWeekRhythm(schedule, dateStr);
+}
+
+/** The Sunday `offset` weeks after the week of `todayKey`: a rhythm's anchor. */
+export function rhythmAnchor(todayKey, offset = 0) {
+ return addDays(weekStartKey(todayKey), 7 * (Number(offset) || 0));
+}
+
+/** How many weeks from this one the next week of a rhythm is: 0 for this week. */
+export function rhythmOffset(todayKey, anchor, every) {
+ if (!isRhythm(every, anchor)) return 0;
+ const n = Number(every);
+ return ((weeksBetweenKeys(todayKey, anchor) % n) + n) % n;
+}
+
const STICKY_DURATIONS = ['until-completed', 'once-completed', 'any-day'];
/**
@@ -72,7 +120,7 @@ export function dueOn(schedule, dateStr) {
if (schedule.crontab && STICKY_DURATIONS.includes(schedule.duration)) return null;
if (schedule.parent_duration === 'any-day' && schedule.due_date) return dateStr === schedule.due_date;
if (!schedule.crontab) return true;
- return cronFiresOn(schedule.crontab, dateStr);
+ return scheduleFiresOn(schedule, dateStr);
}
/**
diff --git a/client/src/utils/choreHelpers.js b/client/src/utils/choreHelpers.js
index d48e404d..f09d1138 100644
--- a/client/src/utils/choreHelpers.js
+++ b/client/src/utils/choreHelpers.js
@@ -1,11 +1,12 @@
import { getServerTimezoneSync } from './timezone.js';
-import { cronFiresOn, localDateOf } from './choreDays.js';
+import { scheduleFiresOn, localDateOf } from './choreDays.js';
// Whether a chore is on today's list. "Today" is the household's date (the
// server's time zone), not the browser's: a display in another zone must
// show the same chores as the server counts for the daily bonus. The
-// crontab is matched on that date's calendar fields, as the server's
-// cronFiresOnDate and the history row's cronFiresOn do.
+// crontab is matched on that date's calendar fields, and a schedule repeating
+// every few weeks on its weeks only (issue #401), as the server's
+// scheduleFiresOnDate and the history row's scheduleFiresOn do.
export function shouldShowChoreToday(schedule, today = getTodayDateString()) {
if (!schedule.visible) {
return false;
@@ -21,7 +22,7 @@ export function shouldShowChoreToday(schedule, today = getTodayDateString()) {
return true;
}
- return cronFiresOn(schedule.crontab, today);
+ return scheduleFiresOn(schedule, today);
}
/**
diff --git a/client/src/utils/choreScheduleGroups.js b/client/src/utils/choreScheduleGroups.js
index 95125ed3..1487ca84 100644
--- a/client/src/utils/choreScheduleGroups.js
+++ b/client/src/utils/choreScheduleGroups.js
@@ -5,7 +5,8 @@
// schedules the same way.
//
// A timing is { kind, key, ... }:
-// week { days: [0..6] } days of the week (0 = Sunday, as crontab)
+// week { days: [0..6] } days of the week (0 = Sunday, as crontab);
+// with every (2-4) and anchor (a Sunday), every few weeks (#401)
// everyN { n } every n days ("*/n" day of month)
// monthly { dom: '1' | '1,15' } days of the month
// months { dom: 15, months: [1,4,7,10], every: 3 } one day in some
@@ -18,7 +19,7 @@
// each schedule's own, and are kept when its group's days change.
import { CronExpressionParser } from 'cron-parser';
-import { addDays, cronFiresOn, localDateOf } from './choreDays.js';
+import { addDays, cronFiresOn, localDateOf, scheduleFiresOn, weeksBetweenKeys, WEEK_INTERVALS } from './choreDays.js';
const ALL_DAYS = [0, 1, 2, 3, 4, 5, 6];
@@ -86,7 +87,7 @@ export function timingOfSchedule(schedule) {
if (!f) return { kind: 'custom', key: `custom:${schedule.crontab}`, rest: schedule.crontab };
if (f.mon === '*' && f.dom === '*') {
const days = parseDaysOfWeek(f.dow);
- if (days && days.length) return { kind: 'week', key: `week:${days.join(',')}`, days };
+ if (days && days.length) return weekTiming(days, schedule.week_interval, schedule.week_anchor);
}
if (f.mon === '*' && (f.dow === '*' || f.dow === '?')) {
const every = f.dom.match(/^\*\/(\d+)$/);
@@ -143,9 +144,18 @@ export function monthsFromStart(startDate, every) {
}
// Timings built from scratch (the Add menu's choices).
-export const weekTiming = (days) => {
+// Every few weeks (issue #401): `every` 2-4 weeks, counted from the week of
+// `anchor`. The key holds which of those weeks it is (its phase), not the
+// anchor itself, so two schedules on the same weeks share a group.
+const RHYTHM_EPOCH = '1970-01-04'; // a Sunday
+export const weekTiming = (days, every = 1, anchor = null) => {
const sorted = [...new Set(days)].sort((a, b) => a - b);
- return { kind: 'week', key: `week:${sorted.join(',')}`, days: sorted };
+ const n = Number(every);
+ if (!WEEK_INTERVALS.includes(n) || !/^\d{4}-\d{2}-\d{2}$/.test(String(anchor || ''))) {
+ return { kind: 'week', key: `week:${sorted.join(',')}`, days: sorted };
+ }
+ const phase = ((weeksBetweenKeys(RHYTHM_EPOCH, anchor) % n) + n) % n;
+ return { kind: 'week', key: `week:${sorted.join(',')}/${n}:${phase}`, days: sorted, every: n, anchor: String(anchor).slice(0, 10), phase };
};
export const everyNTiming = (n) => ({ kind: 'everyN', key: `every:${n}`, n });
export const monthlyTiming = (dom) => {
@@ -216,19 +226,23 @@ export function scheduleFieldsForTiming(timing, schedule = null) {
// showing on its day.
const wasAfter = schedule?.duration === 'once-completed' || schedule?.duration === 'any-day';
const keepDuration = schedule && !wasAfter ? (schedule.duration || 'day-of') : 'day-of';
+ // Every few weeks belongs to a week timing only (issue #401).
+ const noRhythm = { week_interval: null, week_anchor: null };
switch (timing.kind) {
case 'anyDay':
- return { crontab: ANY_DAY_CRONTAB, duration: 'any-day', interval: timing.period };
+ return { crontab: ANY_DAY_CRONTAB, duration: 'any-day', interval: timing.period, ...noRhythm };
case 'once':
- return { crontab: null, duration: 'day-of', interval: null, due_date: timing.dueDate || null };
+ return { crontab: null, duration: 'day-of', interval: null, due_date: timing.dueDate || null, ...noRhythm };
case 'after':
return {
crontab: old && schedule?.crontab ? schedule.crontab : '0 0 * * *',
duration: 'once-completed',
interval: timing.interval,
+ ...noRhythm,
};
default: {
- const fields = { crontab: `${time} ${dayFieldsOf(timing)}`, duration: keepDuration, interval: null };
+ const rhythm = timing.kind === 'week' && timing.every ? { week_interval: timing.every, week_anchor: timing.anchor } : noRhythm;
+ const fields = { crontab: `${time} ${dayFieldsOf(timing)}`, duration: keepDuration, interval: null, ...rhythm };
// A one-time chore's date means nothing once it repeats.
if (schedule && !schedule.crontab) fields.due_date = null;
return fields;
@@ -251,7 +265,8 @@ export function compareTimings(a, b) {
const db = (b.days[i] + 6) % 7;
if (da !== db) return da - db;
}
- return 0;
+ // Every week before every other week, then by which of the weeks.
+ return (a.every || 1) - (b.every || 1) || (a.phase || 0) - (b.phase || 0);
}
if (a.kind === 'everyN') return a.n - b.n;
if (a.kind === 'anyDay') return ANY_DAY_PERIODS.indexOf(a.period) - ANY_DAY_PERIODS.indexOf(b.period);
@@ -299,7 +314,8 @@ export const COMMON_TIMINGS = [
export function timingFallsOn(timing, date, { schedule = null, tz } = {}) {
switch (timing.kind) {
case 'week':
- return timing.days.includes(date.getDay());
+ return timing.days.includes(date.getDay())
+ && (!timing.every || scheduleFiresOn({ crontab: '0 0 * * *', week_interval: timing.every, week_anchor: timing.anchor }, dateKeyOf(date)));
case 'once': {
if (!timing.dueDate) return null;
const key = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
@@ -442,7 +458,7 @@ export function calendarWeek({ groups, dates, today, rows = [], vacation = null,
const next = s.visible ? nextFireOn(s.crontab, today) : null;
if (next) dueKeys = [next]; else placeable = false;
} else if (s.crontab) {
- dueKeys = dates.filter((d) => cronFiresOn(s.crontab, d));
+ dueKeys = dates.filter((d) => scheduleFiresOn(s, d));
}
// Nothing was due before the schedule existed (created_at is UTC; its
// date is close enough for marking past days).
diff --git a/client/src/utils/choreScheduleGroups.test.js b/client/src/utils/choreScheduleGroups.test.js
index 0cfafff6..92d8ca3c 100644
--- a/client/src/utils/choreScheduleGroups.test.js
+++ b/client/src/utils/choreScheduleGroups.test.js
@@ -67,25 +67,25 @@ describe('scheduleFieldsForTiming', () => {
it('keeps a moved schedule\'s time of day and sticky setting', () => {
const s = { crontab: '30 7 * * *', duration: 'until-completed' };
expect(scheduleFieldsForTiming(weekTiming([1, 3, 5]), s))
- .toEqual({ crontab: '30 7 * * 1,3,5', duration: 'until-completed', interval: null });
+ .toEqual({ crontab: '30 7 * * 1,3,5', duration: 'until-completed', interval: null, week_interval: null, week_anchor: null });
});
it('writes every day as *, and new schedules at midnight, showing that day only', () => {
expect(scheduleFieldsForTiming(weekTiming([0, 1, 2, 3, 4, 5, 6])))
- .toEqual({ crontab: '0 0 * * *', duration: 'day-of', interval: null });
+ .toEqual({ crontab: '0 0 * * *', duration: 'day-of', interval: null, week_interval: null, week_anchor: null });
expect(scheduleFieldsForTiming(everyNTiming(2)).crontab).toBe('0 0 */2 * *');
expect(scheduleFieldsForTiming(monthlyTiming('1')).crontab).toBe('0 0 1 * *');
});
it('moves into and out of one-time and again-after-done', () => {
expect(scheduleFieldsForTiming(onceTiming('2026-11-03'), { crontab: '0 0 * * *', duration: 'until-completed' }))
- .toEqual({ crontab: null, duration: 'day-of', interval: null, due_date: '2026-11-03' });
+ .toEqual({ crontab: null, duration: 'day-of', interval: null, due_date: '2026-11-03', week_interval: null, week_anchor: null });
expect(scheduleFieldsForTiming(weekTiming([6]), { crontab: null, due_date: '2026-11-03' }))
- .toEqual({ crontab: '0 0 * * 6', duration: 'day-of', interval: null, due_date: null });
+ .toEqual({ crontab: '0 0 * * 6', duration: 'day-of', interval: null, due_date: null, week_interval: null, week_anchor: null });
expect(scheduleFieldsForTiming(afterTiming('3d'), { crontab: '0 8 * * 1', duration: 'day-of' }))
- .toEqual({ crontab: '0 8 * * 1', duration: 'once-completed', interval: '3d' });
+ .toEqual({ crontab: '0 8 * * 1', duration: 'once-completed', interval: '3d', week_interval: null, week_anchor: null });
expect(scheduleFieldsForTiming(weekTiming([1]), { crontab: '0 8 * * *', duration: 'once-completed', interval: '3d' }))
- .toEqual({ crontab: '0 8 * * 1', duration: 'day-of', interval: null });
+ .toEqual({ crontab: '0 8 * * 1', duration: 'day-of', interval: null, week_interval: null, week_anchor: null });
});
it('round-trips: a moved schedule lands in the group it was moved to', () => {
@@ -332,9 +332,9 @@ describe('once in a period, any day', () => {
});
it('writes its period, and moving off it goes back to a day', () => {
- expect(scheduleFieldsForTiming(anyDayTiming('1m'))).toEqual({ crontab: '0 0 * * *', duration: 'any-day', interval: '1m' });
+ expect(scheduleFieldsForTiming(anyDayTiming('1m'))).toEqual({ crontab: '0 0 * * *', duration: 'any-day', interval: '1m', week_interval: null, week_anchor: null });
const moved = scheduleFieldsForTiming(weekTiming([1, 3]), { crontab: '0 0 * * *', duration: 'any-day', interval: '1w' });
- expect(moved).toEqual({ crontab: '0 0 * * 1,3', duration: 'day-of', interval: null });
+ expect(moved).toEqual({ crontab: '0 0 * * 1,3', duration: 'day-of', interval: null, week_interval: null, week_anchor: null });
expect(timingFallsOn(anyDayTiming('1w'), new Date(2026, 9, 25))).toBeNull();
});
diff --git a/client/src/utils/weekRhythm.test.js b/client/src/utils/weekRhythm.test.js
new file mode 100644
index 00000000..99b65f66
--- /dev/null
+++ b/client/src/utils/weekRhythm.test.js
@@ -0,0 +1,164 @@
+import { describe, it, expect, vi, afterEach } from 'vitest';
+
+// The household's today, which "starting this week" counts from.
+const clock = vi.hoisted(() => ({ today: '2026-12-02' })); // a Wednesday
+vi.mock('./timezone.js', () => ({ getServerTimezoneSync: () => 'UTC' }));
+vi.mock('./choreHelpers.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return { ...actual, getTodayDateString: () => clock.today };
+});
+
+import { weekStartKey, weeksBetweenKeys, onWeekRhythm, scheduleFiresOn, rhythmAnchor, rhythmOffset, dueOn } from './choreDays.js';
+import { shouldShowChoreToday } from './choreHelpers.js';
+import {
+ weekTiming,
+ timingOfSchedule,
+ scheduleFieldsForTiming,
+ compareTimings,
+ groupSchedulesForUser,
+ timingFallsOn,
+ calendarWeek,
+} from './choreScheduleGroups.js';
+import { WIZARD_START, wizardTiming } from '../components/ScheduleWizard.jsx';
+
+// Issue #401: chores every N weeks on set weekdays. Sundays in this file:
+// Nov 29, Dec 6, Dec 13, Dec 20, Dec 27 2026.
+const everyOtherSunday = { crontab: '0 0 * * 0', duration: 'day-of', week_interval: 2, week_anchor: '2026-11-29' };
+
+afterEach(() => { clock.today = '2026-12-02'; });
+
+describe('the rule', () => {
+ it('finds the Sunday of a week, and whole weeks between two dates', () => {
+ expect(weekStartKey('2026-12-02')).toBe('2026-11-29');
+ expect(weekStartKey('2026-11-29')).toBe('2026-11-29');
+ expect(weekStartKey('2026-12-05')).toBe('2026-11-29');
+ expect(weeksBetweenKeys('2026-11-29', '2026-12-13')).toBe(2);
+ expect(weeksBetweenKeys('2026-12-13', '2026-11-30')).toBe(-2);
+ // Across a year end.
+ expect(weeksBetweenKeys('2026-12-27', '2027-01-10')).toBe(2);
+ });
+
+ it('counts the anchor week and every other one, before and after it', () => {
+ const due = ['2026-11-15', '2026-11-29', '2026-12-13', '2026-12-27', '2027-01-10'];
+ const off = ['2026-11-22', '2026-12-06', '2026-12-20', '2027-01-03'];
+ for (const day of due) expect(scheduleFiresOn(everyOtherSunday, day), day).toBe(true);
+ for (const day of off) expect(scheduleFiresOn(everyOtherSunday, day), day).toBe(false);
+ // Only on its weekday, of course.
+ expect(scheduleFiresOn(everyOtherSunday, '2026-11-30')).toBe(false);
+ });
+
+ it('every 3 weeks, on several days of the week', () => {
+ const s = { crontab: '0 0 * * 1,4', week_interval: 3, week_anchor: '2026-11-29' };
+ expect(['2026-11-30', '2026-12-03', '2026-12-21', '2026-12-24'].every((d) => scheduleFiresOn(s, d))).toBe(true);
+ expect(['2026-12-07', '2026-12-10', '2026-12-14', '2026-12-17'].some((d) => scheduleFiresOn(s, d))).toBe(false);
+ });
+
+ it('without a rhythm, or with a broken one, a schedule is every week', () => {
+ for (const s of [
+ { crontab: '0 0 * * 0' },
+ { crontab: '0 0 * * 0', week_interval: 2, week_anchor: null },
+ { crontab: '0 0 * * 0', week_interval: 7, week_anchor: '2026-11-29' },
+ ]) {
+ expect(onWeekRhythm(s, '2026-12-06')).toBe(true);
+ expect(scheduleFiresOn(s, '2026-12-06')).toBe(true);
+ }
+ });
+
+ it('turns "starting next week" into an anchor, and an anchor back into it', () => {
+ expect(rhythmAnchor('2026-12-02', 0)).toBe('2026-11-29');
+ expect(rhythmAnchor('2026-12-02', 1)).toBe('2026-12-06');
+ expect(rhythmOffset('2026-12-02', '2026-11-29', 2)).toBe(0);
+ expect(rhythmOffset('2026-12-02', '2026-12-06', 2)).toBe(1);
+ // An old anchor: Jan 11 is 46 weeks before Nov 29, so the same fortnight;
+ // Jan 4 is 47 weeks before, so the other one.
+ expect(rhythmOffset('2026-12-02', '2026-01-11', 2)).toBe(0);
+ expect(rhythmOffset('2026-12-02', '2026-01-04', 2)).toBe(1);
+ // Every 3 weeks from Jan 11: Dec 13 (48 weeks on) is next, 2 weeks away.
+ expect(rhythmOffset('2026-12-02', '2026-01-11', 3)).toBe(2);
+ });
+});
+
+describe('due today, and the 7-day row', () => {
+ it('shows the chore on its weeks only', () => {
+ const visible = { ...everyOtherSunday, visible: 1 };
+ expect(shouldShowChoreToday(visible, '2026-12-13')).toBe(true);
+ expect(shouldShowChoreToday(visible, '2026-12-06')).toBe(false);
+ });
+
+ it('is due on its weeks only, so the off weeks are "off", not missed', () => {
+ const assigned = { ...everyOtherSunday, user_id: 3, clam_value: 0 };
+ expect(dueOn(assigned, '2026-12-13')).toBe(true);
+ expect(dueOn(assigned, '2026-12-06')).toBe(false);
+ });
+});
+
+describe('timings', () => {
+ it('a rhythm is part of the timing, and of its key, by phase', () => {
+ const a = weekTiming([0], 2, '2026-11-29');
+ const sameWeeks = weekTiming([0], 2, '2026-01-11'); // the same weeks, an older anchor
+ const otherWeeks = weekTiming([0], 2, '2026-12-06');
+ expect(a).toMatchObject({ kind: 'week', days: [0], every: 2, anchor: '2026-11-29' });
+ expect(a.key).toBe(sameWeeks.key);
+ expect(a.key).not.toBe(otherWeeks.key);
+ expect(a.key).not.toBe(weekTiming([0]).key);
+ // Every week stays as it was.
+ expect(weekTiming([0], 1, '2026-11-29')).toEqual(weekTiming([0]));
+ });
+
+ it('reads a schedule\'s rhythm, and writes it back', () => {
+ const timing = timingOfSchedule(everyOtherSunday);
+ expect(timing).toMatchObject({ kind: 'week', every: 2, anchor: '2026-11-29' });
+ expect(scheduleFieldsForTiming(timing)).toEqual({
+ crontab: '0 0 * * 0', duration: 'day-of', interval: null, week_interval: 2, week_anchor: '2026-11-29',
+ });
+ });
+
+ it('moving a fortnightly chore to another kind of timing takes the rhythm away', () => {
+ const monthly = timingOfSchedule({ crontab: '0 0 15 * *', duration: 'day-of' });
+ expect(scheduleFieldsForTiming(monthly, everyOtherSunday)).toMatchObject({ week_interval: null, week_anchor: null });
+ expect(scheduleFieldsForTiming(weekTiming([0]), everyOtherSunday)).toMatchObject({ week_interval: null, week_anchor: null });
+ });
+
+ it('groups every week before every other week, and opposite weeks apart', () => {
+ const schedules = [
+ { id: 1, user_id: 3, title: 'B', ...everyOtherSunday },
+ { id: 2, user_id: 3, title: 'A', crontab: '0 0 * * 0', duration: 'day-of' },
+ { id: 3, user_id: 3, title: 'C', crontab: '0 0 * * 0', duration: 'day-of', week_interval: 2, week_anchor: '2026-12-06' },
+ { id: 4, user_id: 3, title: 'D', crontab: '0 9 * * 0', duration: 'day-of', week_interval: 2, week_anchor: '2025-11-30' },
+ ];
+ const groups = groupSchedulesForUser(schedules, 3);
+ // Every week first; the two fortnights are separate groups.
+ expect(groups[0].schedules.map((s) => s.id)).toEqual([2]);
+ expect(groups.slice(1).map((g) => g.schedules.map((s) => s.id)).sort()).toEqual([[1, 4], [3]]);
+ expect(compareTimings(weekTiming([0]), weekTiming([0], 2, '2026-11-29'))).toBeLessThan(0);
+ });
+
+ it('falls on a date only in its weeks', () => {
+ const timing = weekTiming([0], 2, '2026-11-29');
+ expect(timingFallsOn(timing, new Date(2026, 11, 13))).toBe(true);
+ expect(timingFallsOn(timing, new Date(2026, 11, 6))).toBe(false);
+ });
+
+ it('the board calendar marks only the weeks it is due', () => {
+ const groups = groupSchedulesForUser([{ id: 1, chore_id: 9, user_id: 3, title: 'Cleaners', visible: 1, created_at: '2026-11-01 00:00:00', ...everyOtherSunday }], 3);
+ const dates = (start) => Array.from({ length: 7 }, (_, i) => {
+ const d = new Date(`${start}T12:00:00Z`);
+ d.setUTCDate(d.getUTCDate() + i);
+ return d.toISOString().slice(0, 10);
+ });
+ const onWeek = calendarWeek({ groups, dates: dates('2026-12-13'), today: '2026-12-02' });
+ const offWeek = calendarWeek({ groups, dates: dates('2026-12-06'), today: '2026-12-02' });
+ expect(onWeek.days[0].items.map((i) => i.state)).toEqual(['planned']);
+ expect(offWeek.days.every((day) => day.items.length === 0)).toBe(true);
+ });
+});
+
+describe('the wizard', () => {
+ it('every week is as before; every 2 weeks starts this week or next', () => {
+ const base = { ...WIZARD_START, how: 'days', days: [0] };
+ expect(wizardTiming(base)).toEqual(weekTiming([0]));
+ expect(wizardTiming({ ...base, every: 2, offset: 0 })).toMatchObject({ every: 2, anchor: '2026-11-29' });
+ expect(wizardTiming({ ...base, every: 2, offset: 1 })).toMatchObject({ every: 2, anchor: '2026-12-06' });
+ expect(wizardTiming({ ...base, every: 4, offset: 3 })).toMatchObject({ every: 4, anchor: '2026-12-20' });
+ });
+});
diff --git a/docs/architecture/database.md b/docs/architecture/database.md
index 330db99d..97145076 100644
--- a/docs/architecture/database.md
+++ b/docs/architecture/database.md
@@ -90,6 +90,8 @@ sound_enabled, -- 0/1: play a notification sound at due_time
sound, -- chosen sound filename; null = use global default
reminder_interval_minutes, -- null/0 = ring once; N = repeat every N min until completed
due_date, -- 'YYYY-MM-DD' calendar deadline (nullable; drives yellow/red urgency, #97)
+week_interval, -- 2, 3 or 4: every that many weeks; NULL = every week (#401, migration 45)
+week_anchor, -- 'YYYY-MM-DD', the Sunday of a week that counts; NULL without week_interval
visible, created_at
```
diff --git a/docs/reference/backend-api.md b/docs/reference/backend-api.md
index d1d76cfd..bdb0b5b1 100644
--- a/docs/reference/backend-api.md
+++ b/docs/reference/backend-api.md
@@ -219,7 +219,7 @@ Every recipient (a device's browser push, an ntfy topic, a Home Assistant phone)
| GET/POST | `/api/chores` | List / create chore definitions. Each listed chore carries `followups: [{ id, followup_chore_id, title }]`. `claim_user_ids` is who a bonus chore is offered to (issue #403): a list of user ids, `null` (the default) for everyone, or `[]` for nobody; an unknown id answers **400**. |
| PATCH/DELETE | `/api/chores/:id` | Update / delete a chore. PATCH changes `claim_user_ids` only when it is sent. Deleting removes its follow-up rules and any rule that names it. |
| GET/PUT | `/api/chores/:id/followups` | A chore's follow-ups (issue #241). PUT replaces them with `{ followups: [{ followup_chore_id, user_ids, delay_minutes }] }`: at most 3, not the chore itself, no loops, at least one person, delay 0–10080 minutes. |
-| GET/POST | `/api/chore-schedules` | List (filter by `user_id`, `visible`, `usage`, `chore_id`) / create. `duration` is `day-of` (default), `until-completed`, `once-completed` (with an `interval` such as `3d`) or `any-day` (once in a period, any day: `interval` is its period, one of `1w`, `2w`, `1m`, `3m`, `6m`, `1y`, default `1w`; its crontab is set to `0 0 * * *` whatever is sent). `weekly` is accepted as `any-day` every `1w`. Each row carries `parent_duration`, the duration of the schedule a sticky chore's card came from (an `any-day` card is due on its `due_date`, its period's last day). Each row also carries its chore's `claim_user_ids` (read-only here; it is set on the chore). Accepts `due_time` (`HH:MM`), `sound`, `sound_enabled`, `reminder_interval_minutes` for due-time sounds, and `due_date` (`YYYY-MM-DD`) for calendar deadlines. `expire_minutes` (one of 0, 15, 30, 60, 120, 180, 240, 360, 480, 720, or null) makes it expire that long after its due time; it needs a `due_time` (400 otherwise), and clearing the due time clears it. PATCH `user_id` reassigns a chore and re-checks the daily bonus for both owners; with `transfer: true` (the dashboard's Transfer dialog) it answers **403** (`code: "CHORE_NOT_OFFERED"`) when a bonus chore's `claim_user_ids` does not include the new person, while an admin's assignment, sent without it, is not held to the list. Taking a chore off someone's day (deleting its schedule or chore, hiding it, moving it to other days, snoozing it, giving the chore clams, or deleting a routine) re-checks their bonus too, and pays it if the rest of the day is done; it never takes a bonus back (issue #298). Deleting an `any-day` schedule, or PATCHing it to another duration, removes its not-yet-done card. PATCHing a repeating schedule's crontab to null (one-time) sets `one_time_after_history_id`, so only completions logged after it mark the one-time chore done. |
+| GET/POST | `/api/chore-schedules` | List (filter by `user_id`, `visible`, `usage`, `chore_id`) / create. `duration` is `day-of` (default), `until-completed`, `once-completed` (with an `interval` such as `3d`) or `any-day` (once in a period, any day: `interval` is its period, one of `1w`, `2w`, `1m`, `3m`, `6m`, `1y`, default `1w`; its crontab is set to `0 0 * * *` whatever is sent). `weekly` is accepted as `any-day` every `1w`. `week_interval` (2, 3 or 4, or null for every week) and `week_anchor` (`YYYY-MM-DD`, stored as its week's Sunday; this week when left out) make a schedule every few weeks on its days (issue #401): only with a days-of-the-week crontab on a `day-of` or `until-completed` schedule, **400** otherwise. A PATCH that changes the crontab or duration so that it can't have one, without sending them, drops it; one that only changes the days keeps it. Each row carries `parent_duration`, the duration of the schedule a sticky chore's card came from (an `any-day` card is due on its `due_date`, its period's last day). Each row also carries its chore's `claim_user_ids` (read-only here; it is set on the chore). Accepts `due_time` (`HH:MM`), `sound`, `sound_enabled`, `reminder_interval_minutes` for due-time sounds, and `due_date` (`YYYY-MM-DD`) for calendar deadlines. `expire_minutes` (one of 0, 15, 30, 60, 120, 180, 240, 360, 480, 720, or null) makes it expire that long after its due time; it needs a `due_time` (400 otherwise), and clearing the due time clears it. PATCH `user_id` reassigns a chore and re-checks the daily bonus for both owners; with `transfer: true` (the dashboard's Transfer dialog) it answers **403** (`code: "CHORE_NOT_OFFERED"`) when a bonus chore's `claim_user_ids` does not include the new person, while an admin's assignment, sent without it, is not held to the list. Taking a chore off someone's day (deleting its schedule or chore, hiding it, moving it to other days, snoozing it, giving the chore clams, or deleting a routine) re-checks their bonus too, and pays it if the rest of the day is done; it never takes a bonus back (issue #298). Deleting an `any-day` schedule, or PATCHing it to another duration, removes its not-yet-done card. PATCHing a repeating schedule's crontab to null (one-time) sets `one_time_after_history_id`, so only completions logged after it mark the one-time chore done. |
| GET/PATCH/DELETE | `/api/chore-schedules/:id` | Single schedule CRUD. |
| POST | `/api/chore-schedules/:id/claim` | Claim a bonus chore from the pool for a kid: body `{ user_id }`. Records the claim date on the schedule (`pool_claimed_on`); the nightly job returns only schedules carrying that marker to the pool, and clears it as it goes. Answers **409** when the chore is already assigned, not visible, pays no clams, or the kid already has an open bonus chore, and **403** (`code: "CHORE_NOT_OFFERED"`) when the chore's `claim_user_ids` does not include the kid. An admin assigning the same chore with PATCH sets no marker. |
| POST | `/api/chore-schedules/bulk` | Bulk create schedules. |
diff --git a/docs/reference/features.md b/docs/reference/features.md
index 020ac40a..b1db6c39 100644
--- a/docs/reference/features.md
+++ b/docs/reference/features.md
@@ -53,6 +53,23 @@ The chore system uses a **three-table model** (see [Database](../architecture/da
- **Recurrence** is expressed as cron (`crontab`). A `NULL` crontab means a
one-time instance.
+- **Every few weeks on set days** (issue #401): "every other Sunday" for the
+ cleaners who come fortnightly. Cron can't say it (it has no week number), so
+ the rhythm sits beside the crontab: `week_interval` (2, 3 or 4; NULL is every
+ week) and `week_anchor` (the Sunday of a week that counts). A day counts when
+ the crontab fires and its week is a whole number of intervals from the
+ anchor's week. Only for days of the week (day of month and month `*`), on a
+ `day-of` or `until-completed` schedule: "stays until done" keeps its
+ Sundays however late it's ticked. In an off week the chore isn't due at
+ all: no card, no hold on the daily bonus, no miss, "off" in the 7-day row.
+ Set it in the wizard's *On certain days of the week* (Every … weeks,
+ starting this week or a later one) or a group's **Change days**; the
+ board names it "Every other week: Sunday (next Dec 13)". Changing a
+ schedule's days keeps it; moving it to another kind of timing drops it, and
+ so does the server when an editor that doesn't know about it moves it
+ off days of the week. Code: `server/utils/weekRhythm.js`,
+ `scheduleFiresOnDate` in `server/utils/cronDay.js` (every "is it due"
+ check), and `scheduleFiresOn` in `client/src/utils/choreDays.js`.
- **Duration** controls persistence:
- `day-of` — shows only on the scheduled day.
- `until-completed` — a "sticky" chore that stays until done.
diff --git a/server/index.js b/server/index.js
index 070ee873..d06484f6 100644
--- a/server/index.js
+++ b/server/index.js
@@ -94,7 +94,8 @@ const crypto = require('crypto');
const axios = require('axios');
const ICAL = require('ical.js');
const { CronExpressionParser } = require('cron-parser');
-const { cronFiresOnDate } = require('./utils/cronDay');
+const { scheduleFiresOnDate } = require('./utils/cronDay');
+const weekRhythm = require('./utils/weekRhythm');
const points = require('./utils/points');
const anyDayChores = require('./services/anyDayChores');
const choreExpiry = require('./utils/choreExpiry');
@@ -2476,7 +2477,7 @@ function spawnStickyChildren(today, scheduleIds = null) {
const stickyParentSchedules = db.prepare(`
SELECT cs.id, cs.chore_id, cs.user_id, cs.crontab, cs.duration, cs.interval,
cs.created_at, cs.due_date, cs.due_time, cs.sound_enabled, cs.sound, cs.reminder_interval_minutes,
- cs.expire_minutes
+ cs.expire_minutes, cs.week_interval, cs.week_anchor
FROM chore_schedules cs
WHERE cs.crontab IS NOT NULL
AND cs.duration IN ('until-completed', 'once-completed', 'any-day')
@@ -2520,7 +2521,7 @@ function spawnStickyChildren(today, scheduleIds = null) {
try {
firesToday = period
? !doneThisPeriod.get(schedule.id, schedule.id, period.start, today)
- : cronFiresOnDate(schedule.crontab, today);
+ : scheduleFiresOnDate(schedule, today);
} catch (parseError) {
console.warn(`Skipping sticky schedule ${schedule.id} due to invalid crontab: ${schedule.crontab}`);
continue;
@@ -3745,6 +3746,19 @@ fastify.post('/api/chore-schedules', async (request, reply) => {
}
}
+ // Every few weeks (issue #401): only on days of the week, and only for
+ // a day-of or until-completed schedule (utils/weekRhythm.js).
+ const rhythm = weekRhythm.normalizeWeekRhythm({
+ interval: request.body.week_interval,
+ anchor: request.body.week_anchor,
+ crontab,
+ duration: normalizedDuration,
+ today: getTodayLocalDateString(),
+ });
+ if (rhythm.error) {
+ return reply.status(400).send({ error: rhythm.error });
+ }
+
let normalizedParentScheduleId = null;
if (parent_schedule_id !== undefined && parent_schedule_id !== null && parent_schedule_id !== '') {
const parsedParentScheduleId = parseInt(parent_schedule_id, 10);
@@ -3763,7 +3777,7 @@ fastify.post('/api/chore-schedules', async (request, reply) => {
return reply.status(400).send({ error: targets.error });
}
- const stmt = db.prepare('INSERT INTO chore_schedules (chore_id, user_id, crontab, duration, visible, interval, parent_schedule_id, due_time, sound, sound_enabled, reminder_interval_minutes, due_date, transferable, can_snooze, snoozed_until, expire_minutes) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
+ const stmt = db.prepare('INSERT INTO chore_schedules (chore_id, user_id, crontab, duration, visible, interval, parent_schedule_id, due_time, sound, sound_enabled, reminder_interval_minutes, due_date, transferable, can_snooze, snoozed_until, expire_minutes, week_interval, week_anchor) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
// One row per person, all or none: a batch never leaves half the
// family scheduled.
const insertAll = db.transaction((userIds) => userIds.map((userId) => stmt.run(
@@ -3782,7 +3796,9 @@ fastify.post('/api/chore-schedules', async (request, reply) => {
transferable !== undefined ? (transferable ? 1 : 0) : 1,
can_snooze !== undefined ? (can_snooze ? 1 : 0) : 1,
snoozedUntilResult.value,
- expireResult.value
+ expireResult.value,
+ rhythm.value.week_interval,
+ rhythm.value.week_anchor
).lastInsertRowid));
const ids = insertAll(targets.userIds);
// A sticky schedule that fires today shows today, not from midnight.
@@ -3875,7 +3891,7 @@ fastify.patch('/api/chore-schedules/:id', async (request, reply) => {
}
}
- const existingSchedule = db.prepare('SELECT id, chore_id, user_id, crontab, duration, interval, snoozed_until, due_time, expire_minutes, created_at FROM chore_schedules WHERE id = ?').get(id);
+ const existingSchedule = db.prepare('SELECT id, chore_id, user_id, crontab, duration, interval, snoozed_until, due_time, expire_minutes, created_at, week_interval, week_anchor FROM chore_schedules WHERE id = ?').get(id);
if (!existingSchedule) {
return reply.status(404).send({ error: 'Schedule not found' });
}
@@ -3934,8 +3950,34 @@ fastify.patch('/api/chore-schedules/:id', async (request, reply) => {
return reply.status(400).send({ error: 'interval is only allowed for once-completed and any-day schedules' });
}
+ // Every few weeks (issue #401). Sent: checked against the crontab and
+ // duration the schedule will have. Not sent: kept, unless the new
+ // crontab or duration can't have one (moved to monthly, say), when it
+ // goes, so an editor that doesn't know about it can't leave a stray
+ // rhythm behind. Changing only the days keeps it.
+ let nextRhythm = null;
+ if (request.body.week_interval !== undefined || request.body.week_anchor !== undefined) {
+ const rhythm = weekRhythm.normalizeWeekRhythm({
+ interval: request.body.week_interval !== undefined ? request.body.week_interval : existingSchedule.week_interval,
+ anchor: request.body.week_anchor !== undefined ? request.body.week_anchor : existingSchedule.week_anchor,
+ crontab: nextCrontab,
+ duration: nextDuration,
+ today: getTodayLocalDateString(),
+ });
+ if (rhythm.error) {
+ return reply.status(400).send({ error: rhythm.error });
+ }
+ nextRhythm = rhythm.value;
+ } else if (existingSchedule.week_interval && !weekRhythm.canHaveRhythm(nextCrontab, nextDuration)) {
+ nextRhythm = { week_interval: null, week_anchor: null };
+ }
+
const updates = [];
const params = [];
+ if (nextRhythm) {
+ updates.push('week_interval = ?', 'week_anchor = ?');
+ params.push(nextRhythm.week_interval, nextRhythm.week_anchor);
+ }
if (chore_id !== undefined) { updates.push('chore_id = ?'); params.push(chore_id); }
if (user_id !== undefined) {
@@ -4144,7 +4186,7 @@ fastify.post('/api/chore-schedules/:id/claim', async (request, reply) => {
if (row.snoozed_until && new Date(row.snoozed_until) > now) return false;
if (!row.crontab) return true;
try {
- return cronFiresOnDate(row.crontab, today);
+ return scheduleFiresOnDate(row, today);
} catch {
return false;
}
@@ -4414,7 +4456,7 @@ function getTodaysRegularChoresForUser(userId, dateStr, referenceNow = new Date(
}
// ensure only chores that are due today are part of today's chores
- if (cronFiresOnDate(schedule.crontab, dateStr)) {
+ if (scheduleFiresOnDate(schedule, dateStr)) {
todaysChores.push(schedule);
}
}
diff --git a/server/migrations/registry.js b/server/migrations/registry.js
index 502770d8..9e0c16e6 100644
--- a/server/migrations/registry.js
+++ b/server/migrations/registry.js
@@ -45,4 +45,5 @@ module.exports = [
{ schemaId: 42, migrationPath: './migrations/schema42-poolClaimedOn', },
{ schemaId: 43, migrationPath: './migrations/schema43-pluginPermissionGrants', },
{ schemaId: 44, migrationPath: './migrations/schema44-choreClaimUsers', },
+ { schemaId: 45, migrationPath: './migrations/schema45-weekRhythm', },
];
diff --git a/server/migrations/schema45-weekRhythm.js b/server/migrations/schema45-weekRhythm.js
new file mode 100644
index 00000000..195beaa6
--- /dev/null
+++ b/server/migrations/schema45-weekRhythm.js
@@ -0,0 +1,40 @@
+const context = globalThis.__HOMEGLOW_SCHEMA_MIGRATION_CONTEXT;
+
+if (!context || !context.db) {
+ throw new Error('Schema migration context is missing for migration');
+}
+
+const { db, schemaIdKey, targetSchemaId } = context;
+
+try {
+ console.log(`=== Starting week rhythm schema migration to version ${targetSchemaId} ===`);
+
+ db.exec('BEGIN');
+ try {
+ // Every N weeks on set weekdays (issue #401): how many weeks apart
+ // (2, 3 or 4; NULL is every week, as every schedule was before) and
+ // the Sunday of a week that counts (utils/weekRhythm.js).
+ const columns = db.prepare('PRAGMA table_info(chore_schedules)').all().map((c) => c.name);
+ if (!columns.includes('week_interval')) {
+ db.exec('ALTER TABLE chore_schedules ADD COLUMN week_interval INTEGER');
+ }
+ if (!columns.includes('week_anchor')) {
+ db.exec('ALTER TABLE chore_schedules ADD COLUMN week_anchor TEXT');
+ }
+
+ db.prepare('INSERT OR REPLACE INTO settings (key, value) VALUES (?, ?)').run(
+ schemaIdKey,
+ String(targetSchemaId)
+ );
+
+ db.exec('COMMIT');
+ console.log(`=== Week rhythm schema migration completed (version ${targetSchemaId}) ===`);
+ } catch (migrationError) {
+ db.exec('ROLLBACK');
+ throw migrationError;
+ }
+} catch (error) {
+ console.error('=== Week rhythm schema migration failed ===');
+ console.error('Error:', error);
+ throw error;
+}
diff --git a/server/tests/weekRhythm.test.js b/server/tests/weekRhythm.test.js
new file mode 100644
index 00000000..9f01e2d0
--- /dev/null
+++ b/server/tests/weekRhythm.test.js
@@ -0,0 +1,187 @@
+// Every N weeks on set weekdays (issue #401): the rule, and a real server.
+// Sundays used below: Nov 29, Dec 6, Dec 13, Dec 20 2026.
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const { spawn } = require('node:child_process');
+const fs = require('node:fs');
+const path = require('node:path');
+const { freePort } = require('./freePort');
+const weekRhythm = require('../utils/weekRhythm');
+const { scheduleFiresOnDate } = require('../utils/cronDay');
+
+const everyOtherSunday = { crontab: '0 0 * * 0', week_interval: 2, week_anchor: '2026-11-29' };
+
+// ---- The rule.
+
+test('weeks run Sunday to Saturday, counted between any two dates', () => {
+ assert.equal(weekRhythm.weekStartOf('2026-12-02'), '2026-11-29');
+ assert.equal(weekRhythm.weekStartOf('2026-11-29'), '2026-11-29');
+ assert.equal(weekRhythm.weeksBetween('2026-11-29', '2026-12-13'), 2);
+ assert.equal(weekRhythm.weeksBetween('2026-12-13', '2026-11-30'), -2);
+ assert.equal(weekRhythm.weeksBetween('2026-12-27', '2027-01-10'), 2);
+});
+
+test('a schedule fires on its weekday in its weeks only, before and after the anchor', () => {
+ for (const day of ['2026-11-15', '2026-11-29', '2026-12-13', '2027-01-10']) assert.equal(scheduleFiresOnDate(everyOtherSunday, day), true, day);
+ for (const day of ['2026-11-22', '2026-12-06', '2026-12-20']) assert.equal(scheduleFiresOnDate(everyOtherSunday, day), false, day);
+ assert.equal(scheduleFiresOnDate(everyOtherSunday, '2026-11-30'), false);
+ // No rhythm: every week, as before.
+ assert.equal(scheduleFiresOnDate({ crontab: '0 0 * * 0' }, '2026-12-06'), true);
+});
+
+test('a rhythm needs days of the week, on a day-of or until-completed schedule', () => {
+ const today = '2026-12-02';
+ const ok = (fields) => weekRhythm.normalizeWeekRhythm({ crontab: '0 0 * * 0', duration: 'day-of', today, ...fields });
+ assert.deepEqual(ok({ interval: undefined }).value, { week_interval: null, week_anchor: null });
+ assert.deepEqual(ok({ interval: 1 }).value, { week_interval: null, week_anchor: null });
+ // No anchor: this week. An anchor mid-week: its Sunday.
+ assert.deepEqual(ok({ interval: 2 }).value, { week_interval: 2, week_anchor: '2026-11-29' });
+ assert.deepEqual(ok({ interval: '3', anchor: '2026-12-09' }).value, { week_interval: 3, week_anchor: '2026-12-06' });
+ assert.deepEqual(ok({ interval: 2, duration: 'until-completed' }).value, { week_interval: 2, week_anchor: '2026-11-29' });
+ assert.match(ok({ interval: 5 }).error, /one of 2, 3, 4/);
+ assert.match(ok({ interval: 2, anchor: '2026-02-30' }).error, /real date/);
+ assert.match(ok({ interval: 2, crontab: '0 0 15 * *' }).error, /days of the week/);
+ assert.match(ok({ interval: 2, crontab: null }).error, /days of the week/);
+ assert.match(ok({ interval: 2, duration: 'once-completed' }).error, /days of the week/);
+ assert.match(ok({ interval: 2, duration: 'any-day' }).error, /days of the week/);
+});
+
+// ---- A real server.
+
+const serverDir = path.resolve(__dirname, '..');
+const tmpDir = path.resolve(__dirname, '.tmp');
+const testDbPath = path.join(tmpDir, `week-rhythm-${process.pid}-${Date.now()}.db`);
+const keepTestArtifacts = process.env.HOMEGLOW_TEST_KEEP_ARTIFACTS === '1';
+let baseUrl;
+let serverProcess;
+let serverLogs = '';
+const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
+
+async function api(pathname, method = 'GET', body) {
+ const response = await fetch(`${baseUrl}${pathname}`, {
+ method, headers: body ? { 'Content-Type': 'application/json' } : {}, body: body ? JSON.stringify(body) : undefined,
+ });
+ const text = await response.text();
+ let parsed;
+ try { parsed = text ? JSON.parse(text) : null; } catch { parsed = text; }
+ return { status: response.status, body: parsed };
+}
+const ok = (res, what) => { assert.ok(res.status < 300, `${what}: ${res.status} ${JSON.stringify(res.body)}`); return res.body; };
+const schedule = async (id) => (await api('/api/chore-schedules')).body.find((s) => s.id === id);
+// The server's today (TZ is UTC here), and the Sunday of its week.
+const today = () => new Date().toISOString().slice(0, 10);
+const thisSunday = () => weekRhythm.weekStartOf(today());
+const shift = (dateStr, days) => {
+ const d = new Date(`${dateStr}T12:00:00Z`);
+ d.setUTCDate(d.getUTCDate() + days);
+ return d.toISOString().slice(0, 10);
+};
+
+let ava;
+let chore;
+
+test.before(async () => {
+ fs.mkdirSync(tmpDir, { recursive: true });
+ const port = await freePort();
+ baseUrl = `http://127.0.0.1:${port}`;
+ serverProcess = spawn(process.execPath, ['index.js'], {
+ cwd: serverDir,
+ env: {
+ ...process.env, PORT: String(port), DB_PATH: testDbPath, TZ: 'UTC', DEMO_MODE: 'false',
+ ENCRYPTION_KEY: Buffer.alloc(32, 4).toString('base64'),
+ HOMEGLOW_DISABLE_BACKGROUND_JOBS: '1', HOMEGLOW_DISABLE_CALENDAR_SYNC: '1', HOMEGLOW_DISABLE_UPDATE_CHECK: '1',
+ },
+ stdio: ['ignore', 'pipe', 'pipe'],
+ });
+ serverProcess.stdout.on('data', (chunk) => { serverLogs += chunk; });
+ serverProcess.stderr.on('data', (chunk) => { serverLogs += chunk; });
+ const start = Date.now();
+ while (Date.now() - start < 30000) {
+ try { if ((await fetch(`${baseUrl}/api/test`)).ok) break; } catch { /* starting */ }
+ await delay(250);
+ }
+ ava = ok(await api('/api/users', 'POST', { username: 'Ava', email: 'ava@example.com' }), 'user').id;
+ chore = ok(await api('/api/chores', 'POST', { title: 'Put out the cleaners\' check', clam_value: 0 }), 'chore').id;
+});
+
+test.after(async () => {
+ if (serverProcess && serverProcess.exitCode === null) {
+ await new Promise((resolve) => { serverProcess.once('close', resolve); serverProcess.kill(); setTimeout(resolve, 5000); });
+ }
+ if (process.exitCode && serverLogs) console.error(serverLogs.slice(-4000));
+ if (!keepTestArtifacts) {
+ for (const suffix of ['', '-wal', '-shm']) fs.rmSync(`${testDbPath}${suffix}`, { force: true });
+ }
+});
+
+test('a schedule is stored with its rhythm; without an anchor, from this week', async () => {
+ const id = ok(await api('/api/chore-schedules', 'POST', { chore_id: chore, user_id: ava, crontab: '0 0 * * 0', duration: 'day-of', week_interval: 2 }), 'create').id;
+ const row = await schedule(id);
+ assert.equal(row.week_interval, 2);
+ assert.equal(row.week_anchor, thisSunday());
+ // An ordinary schedule has none.
+ const plain = ok(await api('/api/chore-schedules', 'POST', { chore_id: chore, user_id: ava, crontab: '0 0 * * 1', duration: 'day-of' }), 'create').id;
+ assert.equal((await schedule(plain)).week_interval, null);
+});
+
+test('a rhythm is refused where it means nothing', async () => {
+ const send = (fields) => api('/api/chore-schedules', 'POST', { chore_id: chore, user_id: ava, week_interval: 2, ...fields });
+ assert.equal((await send({ crontab: '0 0 15 * *', duration: 'day-of' })).status, 400);
+ assert.equal((await send({ crontab: '0 0 * * 0', duration: 'once-completed', interval: '2w' })).status, 400);
+ assert.equal((await send({ crontab: '0 0 * * 0', duration: 'day-of', week_interval: 6 })).status, 400);
+ assert.equal((await send({ crontab: null, duration: 'day-of' })).status, 400);
+});
+
+test('changing the days keeps the rhythm; moving to monthly drops it; it can be set and changed', async () => {
+ const id = ok(await api('/api/chore-schedules', 'POST', { chore_id: chore, user_id: ava, crontab: '0 0 * * 0', duration: 'day-of', week_interval: 2, week_anchor: '2026-11-29' }), 'create').id;
+ // An editor that knows nothing of the rhythm changes the days: kept.
+ ok(await api(`/api/chore-schedules/${id}`, 'PATCH', { crontab: '0 0 * * 6' }), 'change days');
+ assert.deepEqual([(await schedule(id)).week_interval, (await schedule(id)).week_anchor], [2, '2026-11-29']);
+ // Every 3 weeks from a mid-week date: stored from that week's Sunday.
+ ok(await api(`/api/chore-schedules/${id}`, 'PATCH', { week_interval: 3, week_anchor: '2026-12-09' }), 'change rhythm');
+ assert.deepEqual([(await schedule(id)).week_interval, (await schedule(id)).week_anchor], [3, '2026-12-06']);
+ // A rhythm that doesn't fit what the schedule will be is refused.
+ assert.equal((await api(`/api/chore-schedules/${id}`, 'PATCH', { crontab: '0 0 15 * *', week_interval: 2 })).status, 400);
+ // Moved to monthly without a word about it: the rhythm goes.
+ ok(await api(`/api/chore-schedules/${id}`, 'PATCH', { crontab: '0 0 15 * *' }), 'to monthly');
+ assert.deepEqual([(await schedule(id)).week_interval, (await schedule(id)).week_anchor], [null, null]);
+ // Every week again, explicitly.
+ ok(await api(`/api/chore-schedules/${id}`, 'PATCH', { crontab: '0 0 * * 0', week_interval: 2 }), 'back to fortnightly');
+ ok(await api(`/api/chore-schedules/${id}`, 'PATCH', { week_interval: null }), 'every week');
+ assert.deepEqual([(await schedule(id)).week_interval, (await schedule(id)).week_anchor], [null, null]);
+});
+
+test('"stays until done" makes its card only in the rhythm\'s weeks', async () => {
+ const card = async (parentId) => (await api('/api/chore-schedules')).body.find((s) => s.parent_schedule_id === parentId);
+ const sticky = (chorId, anchor) => api('/api/chore-schedules', 'POST', {
+ chore_id: chorId, user_id: ava, crontab: '0 0 * * *', duration: 'until-completed', week_interval: 2, week_anchor: anchor,
+ });
+ const onChore = ok(await api('/api/chores', 'POST', { title: 'On week', clam_value: 0 }), 'chore').id;
+ const offChore = ok(await api('/api/chores', 'POST', { title: 'Off week', clam_value: 0 }), 'chore').id;
+ const on = ok(await sticky(onChore, thisSunday()), 'sticky on').id;
+ const off = ok(await sticky(offChore, shift(thisSunday(), -7)), 'sticky off').id;
+ assert.ok(await card(on), 'a card for this week');
+ assert.equal(await card(off), undefined, 'no card in an off week');
+});
+
+test('a chore in an off week holds back no daily bonus; in its week it does', async () => {
+ ok(await api('/api/settings', 'POST', { key: 'daily_completion_clam_reward', value: '2' }), 'reward');
+ const bonusToday = async (userId) => (await api(`/api/chore-history?user_id=${userId}&date=${today()}`)).body
+ .filter((row) => row.kind === 'daily_bonus').length;
+ const everyDay = '0 0 * * *';
+ const setUp = async (name, anchor) => {
+ const user = ok(await api('/api/users', 'POST', { username: name, email: `${name}@example.com` }), 'user').id;
+ const daily = ok(await api('/api/chores', 'POST', { title: `${name} daily`, clam_value: 0 }), 'chore').id;
+ const fortnight = ok(await api('/api/chores', 'POST', { title: `${name} fortnightly`, clam_value: 0 }), 'chore').id;
+ const dailyId = ok(await api('/api/chore-schedules', 'POST', { chore_id: daily, user_id: user, crontab: everyDay, duration: 'day-of' }), 'daily').id;
+ ok(await api('/api/chore-schedules', 'POST', { chore_id: fortnight, user_id: user, crontab: everyDay, duration: 'day-of', week_interval: 2, week_anchor: anchor }), 'fortnightly');
+ ok(await api('/api/chores/complete', 'POST', { chore_schedule_id: dailyId, user_id: user, date: today() }), 'complete daily');
+ return user;
+ };
+ // Its week is next week: today's only due chore is done, so the bonus is paid.
+ const offWeek = await setUp('noah', shift(thisSunday(), 7));
+ assert.equal(await bonusToday(offWeek), 1, 'paid: the fortnightly chore is not due this week');
+ // Its week is this week: still due, so no bonus yet.
+ const onWeek = await setUp('mia', thisSunday());
+ assert.equal(await bonusToday(onWeek), 0, 'held back: the fortnightly chore is due today');
+});
diff --git a/server/utils/cronDay.js b/server/utils/cronDay.js
index f7a755cd..15d8349b 100644
--- a/server/utils/cronDay.js
+++ b/server/utils/cronDay.js
@@ -1,4 +1,5 @@
const { CronExpressionParser } = require('cron-parser');
+const weekRhythm = require('./weekRhythm');
const pad = (n) => String(n).padStart(2, '0');
@@ -30,4 +31,14 @@ function cronFiresOnDate(crontab, dateStr) {
return nextDate === dateStr;
}
-module.exports = { cronFiresOnDate };
+/**
+ * Whether a schedule is due on `dateStr`: its crontab fires that day and, for
+ * one repeating every few weeks (issue #401), that week is one of its weeks
+ * (utils/weekRhythm.js). Every place that asks "is this due today" asks
+ * this, so the card, the daily bonus and the misses agree.
+ */
+function scheduleFiresOnDate(schedule, dateStr) {
+ return cronFiresOnDate(schedule.crontab, dateStr) && weekRhythm.onRhythm(schedule, dateStr);
+}
+
+module.exports = { cronFiresOnDate, scheduleFiresOnDate };
diff --git a/server/utils/weekRhythm.js b/server/utils/weekRhythm.js
new file mode 100644
index 00000000..5d3c5dcb
--- /dev/null
+++ b/server/utils/weekRhythm.js
@@ -0,0 +1,91 @@
+// Every N weeks on set weekdays (issue #401): "every other Sunday" for the
+// cleaners who come fortnightly. Cron can't say it, having no week number and
+// no memory of the last run, so the rhythm sits beside the crontab:
+//
+// week_interval 2, 3 or 4 (NULL: every week, as before)
+// week_anchor 'YYYY-MM-DD', the Sunday of a week that counts
+//
+// A day counts when the crontab fires on it AND its week (Sunday to
+// Saturday, as everywhere else) is a whole number of intervals from the
+// anchor's week. Only a weekday crontab can have a rhythm (day of month and
+// month both '*'), and only day-of and until-completed schedules: "again
+// after done" has its own interval, and an any-day chore its own period.
+// The client mirrors this in client/src/utils/choreDays.js.
+
+const WEEK_INTERVALS = [2, 3, 4];
+const RHYTHM_DURATIONS = new Set(['day-of', 'until-completed']);
+const DATE = /^\d{4}-\d{2}-\d{2}$/;
+const DAY_MS = 86400000;
+
+const parseDay = (dateStr) => {
+ const [y, m, d] = String(dateStr).slice(0, 10).split('-').map(Number);
+ return Date.UTC(y, m - 1, d);
+};
+const formatDay = (ms) => new Date(ms).toISOString().slice(0, 10);
+
+/** The Sunday ('YYYY-MM-DD') of the week `dateStr` is in. */
+function weekStartOf(dateStr) {
+ const ms = parseDay(dateStr);
+ return formatDay(ms - new Date(ms).getUTCDay() * DAY_MS);
+}
+
+/** Whole weeks from `fromDate`'s week to `toDate`'s; negative before it. */
+function weeksBetween(fromDate, toDate) {
+ return Math.round((parseDay(weekStartOf(toDate)) - parseDay(weekStartOf(fromDate))) / (7 * DAY_MS));
+}
+
+/** Whether a real calendar date. */
+function isDate(value) {
+ if (typeof value !== 'string' || !DATE.test(value)) return false;
+ return formatDay(parseDay(value)) === value;
+}
+
+/** Whether `dateStr`'s week counts for a schedule (true without a rhythm). */
+function onRhythm(schedule, dateStr) {
+ const every = Number(schedule?.week_interval);
+ if (!WEEK_INTERVALS.includes(every) || !isDate(schedule.week_anchor)) return true;
+ const weeks = weeksBetween(schedule.week_anchor, dateStr);
+ return ((weeks % every) + every) % every === 0;
+}
+
+/** Whether a crontab names days of the week only (any day of month, any month). */
+function isWeekdayCrontab(crontab) {
+ const parts = String(crontab || '').trim().split(/\s+/);
+ if (parts.length === 6) parts.shift();
+ return parts.length === 5 && parts[2] === '*' && parts[3] === '*';
+}
+
+/** Whether a schedule of this crontab and duration may have a rhythm. */
+const canHaveRhythm = (crontab, duration) => Boolean(crontab) && isWeekdayCrontab(crontab) && RHYTHM_DURATIONS.has(duration || 'day-of');
+
+/**
+ * A request's week_interval and week_anchor, checked against the crontab and
+ * duration the schedule will have. `today` anchors a rhythm sent without one.
+ * -> { value: { week_interval, week_anchor } } | { error }
+ */
+function normalizeWeekRhythm({ interval, anchor, crontab, duration, today }) {
+ if (interval === undefined || interval === null || interval === '' || Number(interval) === 1) {
+ return { value: { week_interval: null, week_anchor: null } };
+ }
+ const every = Number(interval);
+ if (!WEEK_INTERVALS.includes(every)) {
+ return { error: `week_interval must be one of ${WEEK_INTERVALS.join(', ')}, or null for every week.` };
+ }
+ if (!canHaveRhythm(crontab, duration)) {
+ return { error: 'Every few weeks needs days of the week (day of month and month "*"), on a day-of or until-completed schedule.' };
+ }
+ if (anchor !== undefined && anchor !== null && anchor !== '' && !isDate(anchor)) {
+ return { error: 'week_anchor must be a real date, YYYY-MM-DD.' };
+ }
+ return { value: { week_interval: every, week_anchor: weekStartOf(anchor || today) } };
+}
+
+module.exports = {
+ WEEK_INTERVALS,
+ weekStartOf,
+ weeksBetween,
+ onRhythm,
+ isWeekdayCrontab,
+ canHaveRhythm,
+ normalizeWeekRhythm,
+};