// Recurring expenses (SPEC.md ยง7.4). There's no server-side scheduler (the // server can't read templates), so whichever client opens the group first // creates the missing occurrences. Their ids are deterministic, so two // clients doing it at once produce the same expense and replay keeps one. import type { Expense, Recurring, RecurringRule, GroupState } from './types.ts'; const MAX_PER_RUN = 120; function parse(d: string): Date { return new Date(`${d}T00:00:00Z`); } function fmt(d: Date): string { return d.toISOString().slice(0, 10); } function daysInMonth(y: number, m: number): number { return new Date(Date.UTC(y, m + 1, 0)).getUTCDate(); } /** The n-th occurrence date (n = 0 is `start`). Monthly/yearly clamp to month end. */ export function nthOccurrence(rule: RecurringRule, n: number): string { const start = parse(rule.start); if (rule.freq === 'weekly') return fmt(new Date(start.getTime() + n * rule.interval * 7 * 864e5)); const months = rule.freq === 'monthly' ? n * rule.interval : n * rule.interval * 12; const y = start.getUTCFullYear() + Math.floor((start.getUTCMonth() + months) / 12); const m = (start.getUTCMonth() + months) % 12; const day = Math.min(start.getUTCDate(), daysInMonth(y, m)); return fmt(new Date(Date.UTC(y, m, day))); } /** All occurrence dates from start up to and including `today`. */ export function occurrencesUntil(rule: RecurringRule, today: string): string[] { const out: string[] = []; for (let n = 0; out.length < 10_000; n++) { const d = nthOccurrence(rule, n); if (d > today || (rule.end && d > rule.end)) break; out.push(d); } return out; } export function occurrenceId(recurringId: string, date: string): string { return `rec-${recurringId}-${date}`; } /** * Occurrences that are due but don't exist yet. Deleted occurrences count * as existing, so deleting one doesn't make it come back. */ export function dueOccurrences(s: GroupState, today: string): Expense[] { const out: Expense[] = []; for (const r of Object.values(s.recurring) as Recurring[]) { for (const date of occurrencesUntil(r.rule, today)) { const id = occurrenceId(r.id, date); if (s.expenses[id]) continue; out.push({ ...structuredClone(r.template), id, date, photo: null, recurringId: r.id }); if (out.length >= MAX_PER_RUN) return out; } } return out; } export function nextOccurrence(rule: RecurringRule, today: string): string | null { for (let n = 0; n < 10_000; n++) { const d = nthOccurrence(rule, n); if (rule.end && d > rule.end) return null; if (d > today) return d; } return null; }