Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion client/src/components/ChoreScheduleBoard.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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,
Expand All @@ -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.
Expand Down Expand Up @@ -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 || '',
Expand All @@ -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;
Expand Down Expand Up @@ -866,6 +875,7 @@ export default function ChoreScheduleBoard({
{DAY_ORDER.map((x) => <ToggleButton key={x} value={x} sx={{ minWidth: 44 }}>{shortDays[x]}</ToggleButton>)}
</ToggleButtonGroup>
)}
{kind === 'week' && <WeekRhythmFields every={d.every || 1} offset={d.offset || 0} onChange={({ every, offset }) => set({ every, offset })} />}
{kind === 'everyN' && (
<TextField size="small" type="number" label={t('chores:board.everyHowManyDays')} value={d.n} onChange={(e) => set({ n: e.target.value })} slotProps={{ htmlInput: { min: 2, max: 31 } }} sx={{ maxWidth: 200 }} />
)}
Expand Down
33 changes: 25 additions & 8 deletions client/src/components/ChoreSchedulesTab.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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 });
Expand Down Expand Up @@ -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),
};

Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -995,7 +1012,7 @@ export default function ChoreSchedulesTab({ setSaveMessage, section, onSection,
<Box component="span" sx={{ display: 'block' }}>
{s.duration === 'any-day'
? t('chores:schedules.anyDayNext')
: `${t('chores:schedules.nextOccurrence')}: ${getNextOccurrence(s.crontab)}`}
: `${t('chores:schedules.nextOccurrence')}: ${getNextOccurrence(s)}`}
</Box>
</>
)}
Expand Down
70 changes: 70 additions & 0 deletions client/src/components/SchedulePicker.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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');
Expand Down Expand Up @@ -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 (
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 1 }}>
<Typography variant="body2" sx={{ fontWeight: 600 }} id="rhythm-every-label">{t('chores:board.rhythm.every')}</Typography>
<ToggleButtonGroup
size="small"
exclusive
value={every}
onChange={(_, value) => 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) => (
<ToggleButton key={n} value={n} sx={{ textTransform: 'none', px: 1.5 }}>
{n === 1 ? t('chores:board.rhythm.week') : t('chores:board.unit_w', { count: n })}
</ToggleButton>
))}
</ToggleButtonGroup>
{every > 1 && (
<>
<Typography variant="body2" sx={{ fontWeight: 600 }} id="rhythm-start-label">{t('chores:board.rhythm.starting')}</Typography>
<ToggleButtonGroup
size="small"
exclusive
value={offset}
onChange={(_, value) => value !== null && onChange({ every, offset: value })}
aria-labelledby="rhythm-start-label"
sx={{ flexWrap: 'wrap' }}
>
{Array.from({ length: every }, (_, k) => (
<ToggleButton key={k} value={k} sx={{ textTransform: 'none', px: 1.5, flexDirection: 'column', lineHeight: 1.2 }}>
<span>{startLabel(k)}</span>
<Typography component="span" variant="caption" color="text.secondary">{t('chores:board.rhythm.weekOf', { date: dateLabel(rhythmAnchor(today, k)) })}</Typography>
</ToggleButton>
))}
</ToggleButtonGroup>
</>
)}
</Box>
);
}

/** Every day / Weekdays / Weekends buttons that fill the day toggles. */
export function QuickDays({ onPick }) {
const { t } = useTranslation(['chores']);
Expand Down
10 changes: 9 additions & 1 deletion client/src/components/ScheduleWizard.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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'];
Expand All @@ -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);
Expand Down Expand Up @@ -166,6 +173,7 @@ export default function ScheduleWizard({ value: w, onChange, onDone, timingLabel
>
{DAY_ORDER.map((d) => <ToggleButton key={d} value={d} sx={{ minWidth: 48 }}>{shortDays[d]}</ToggleButton>)}
</ToggleButtonGroup>
<WeekRhythmFields every={w.every || 1} offset={w.offset || 0} onChange={({ every, offset }) => set({ every, offset })} />
</>
)}

Expand Down
16 changes: 15 additions & 1 deletion client/src/i18n/locales/en/chores.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": {
Expand Down
16 changes: 15 additions & 1 deletion client/src/i18n/locales/es/chores.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": {
Expand Down
50 changes: 49 additions & 1 deletion client/src/utils/choreDays.js
Original file line number Diff line number Diff line change
Expand Up @@ -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'];

/**
Expand All @@ -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);
}

/**
Expand Down
9 changes: 5 additions & 4 deletions client/src/utils/choreHelpers.js
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -21,7 +22,7 @@ export function shouldShowChoreToday(schedule, today = getTodayDateString()) {
return true;
}

return cronFiresOn(schedule.crontab, today);
return scheduleFiresOn(schedule, today);
}

/**
Expand Down
Loading