unit(D1): service CRUD + expandRRULE()
Service template CRUD (create/read/update/deactivate) and the pure expandRRULE() recurrence expander for the RFC 5545 subset (WEEKLY, BIWEEKLY via INTERVAL=2, MONTHLY nth weekday). - src/domain/recurrence.ts: expandRRULE, parseRecurrence, matchesRecurrence, validateRecurrence. Pure — no DB imports. - src/domain/recurrence.test.ts: 13 tests, incl. the 5 required recurrence cases (spring-forward / fall-back Sunday, monthly-nth across a year boundary, cancelled instance not regenerated, biweekly phase stable). - src/db/services.ts + src/app/api/dev/services/route.ts: list/get/ create/update/deactivate; rrule validated on write; deactivate flips active (never delete); 409 on duplicate name. No schema change (services table predates this unit). DST stays in the caller's localToUtc; interval phase anchored to a fixed epoch so biweekly never drifts.
This commit is contained in:
@@ -0,0 +1,113 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
expandRRULE,
|
||||
matchesRecurrence,
|
||||
parseRecurrence,
|
||||
validateRecurrence,
|
||||
} from "./recurrence";
|
||||
import { localToUtc } from "@/lib/tz";
|
||||
|
||||
const TZ = "America/New_York";
|
||||
|
||||
describe("expandRRULE — spring-forward Sunday (DST)", () => {
|
||||
it("lands on the right Sunday and localToUtc keeps 9 AM local across the jump", () => {
|
||||
const dates = expandRRULE("FREQ=WEEKLY;BYDAY=SU", "2026-03-01", "2026-03-12");
|
||||
expect(dates).toEqual(["2026-03-01", "2026-03-08"]);
|
||||
|
||||
// Before the jump the offset is EST (-5); after it is EDT (-4). The local
|
||||
// wall clock stays 09:00 — only the stored UTC hour differs by an hour.
|
||||
const before = localToUtc("2026-03-01", "09:00", TZ);
|
||||
const after = localToUtc("2026-03-08", "09:00", TZ);
|
||||
expect(before.getUTCHours()).toBe(14); // 09:00 EST
|
||||
expect(after.getUTCHours()).toBe(13); // 09:00 EDT
|
||||
});
|
||||
});
|
||||
|
||||
describe("expandRRULE — fall-back Sunday (DST)", () => {
|
||||
it("lands on the right Sunday and the UTC offset shifts back an hour", () => {
|
||||
const dates = expandRRULE("FREQ=WEEKLY;BYDAY=SU", "2026-10-25", "2026-11-03");
|
||||
expect(dates).toEqual(["2026-10-25", "2026-11-01"]);
|
||||
|
||||
const before = localToUtc("2026-10-25", "09:00", TZ); // EDT
|
||||
const after = localToUtc("2026-11-01", "09:00", TZ); // EST
|
||||
expect(before.getUTCHours()).toBe(13);
|
||||
expect(after.getUTCHours()).toBe(14);
|
||||
});
|
||||
});
|
||||
|
||||
describe("expandRRULE — monthly nth across a year boundary", () => {
|
||||
it("keeps the nth weekday of each month across December → January", () => {
|
||||
// 1st Sunday of the month, spanning a year boundary.
|
||||
const dates = expandRRULE("FREQ=MONTHLY;BYDAY=1SU", "2026-12-01", "2027-02-28");
|
||||
expect(dates).toEqual(["2026-12-06", "2027-01-03", "2027-02-07"]);
|
||||
});
|
||||
|
||||
it("resolves the last weekday of the month (-1) correctly", () => {
|
||||
// Last Monday of January 2027 (Jan 1 is a Friday → last Wednesday is the 27th).
|
||||
const dates = expandRRULE("FREQ=MONTHLY;BYDAY=-1WE", "2027-01-01", "2027-01-31");
|
||||
expect(dates).toEqual(["2027-01-27"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("expandRRULE — cancelled instance not regenerated", () => {
|
||||
it("excludes a skip date so a skipped Sunday is never produced", () => {
|
||||
const skip = new Set(["2026-07-05"]);
|
||||
const withSkip = expandRRULE("FREQ=WEEKLY;BYDAY=SU", "2026-07-01", "2026-07-20", {
|
||||
skipDates: skip,
|
||||
});
|
||||
expect(withSkip).toEqual(["2026-07-12", "2026-07-19"]);
|
||||
expect(withSkip).not.toContain("2026-07-05");
|
||||
});
|
||||
});
|
||||
|
||||
describe("expandRRULE — biweekly phase stable", () => {
|
||||
it("stays on the same every-other-week phase with a constant 14-day gap", () => {
|
||||
const dates = expandRRULE("FREQ=WEEKLY;INTERVAL=2;BYDAY=SU", "2026-01-04", "2026-02-28");
|
||||
expect(dates).toEqual(["2026-01-04", "2026-01-18", "2026-02-01", "2026-02-15"]);
|
||||
|
||||
// Every gap is exactly two weeks — the phase never drifts.
|
||||
for (let i = 1; i < dates.length; i++) {
|
||||
const a = Date.parse(dates[i - 1]);
|
||||
const b = Date.parse(dates[i]);
|
||||
expect(b - a).toBe(14 * 24 * 60 * 60 * 1000);
|
||||
}
|
||||
});
|
||||
|
||||
it("INTERVAL=3 lands every third week", () => {
|
||||
const dates = expandRRULE("FREQ=WEEKLY;INTERVAL=3;BYDAY=SU", "2026-01-04", "2026-03-01");
|
||||
expect(dates).toEqual(["2026-01-04", "2026-01-25", "2026-02-15"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseRecurrence", () => {
|
||||
it("normalises BIWEEKLY to WEEKLY INTERVAL=2", () => {
|
||||
const parsed = parseRecurrence("FREQ=BIWEEKLY;BYDAY=SU");
|
||||
expect(parsed.freq).toBe("WEEKLY");
|
||||
expect(parsed.interval).toBe(2);
|
||||
expect(parsed.byDay).toEqual([{ weekday: 0, nth: undefined }]);
|
||||
});
|
||||
|
||||
it("throws on an unsupported FREQ", () => {
|
||||
expect(() => parseRecurrence("FREQ=DAILY;BYDAY=SU")).toThrow();
|
||||
});
|
||||
|
||||
it("throws when BYDAY is missing", () => {
|
||||
expect(() => parseRecurrence("FREQ=WEEKLY")).toThrow();
|
||||
});
|
||||
|
||||
it("matchesRecurrence agrees with the expansion", () => {
|
||||
const parsed = parseRecurrence("FREQ=WEEKLY;BYDAY=SA");
|
||||
expect(matchesRecurrence("2026-06-06", parsed)).toBe(true); // a Saturday
|
||||
expect(matchesRecurrence("2026-06-07", parsed)).toBe(false); // a Sunday
|
||||
});
|
||||
});
|
||||
|
||||
describe("validateRecurrence", () => {
|
||||
it("accepts a valid rule", () => {
|
||||
expect(validateRecurrence("FREQ=WEEKLY;BYDAY=SU")).toEqual([]);
|
||||
});
|
||||
|
||||
it("reports an invalid rule", () => {
|
||||
expect(validateRecurrence("FREQ=WEEKLY;BYDAY=NOPE").length).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,251 @@
|
||||
/**
|
||||
* Recurrence expansion — unit D1 (ARCHITECTURE §5.1, §4.3).
|
||||
*
|
||||
* Pure: no DB, no `src/db` imports. `expandRRULE()` turns an RFC 5545 subset
|
||||
* rule into the list of local dates it lands on inside a window. It is the
|
||||
* single source of truth for "when does this service occur", consumed by the
|
||||
* instance generator (D2) and the seed.
|
||||
*
|
||||
* Supported subset:
|
||||
* FREQ=WEEKLY every week
|
||||
* FREQ=WEEKLY;INTERVAL=n every n-th week (INTERVAL=2 is "biweekly")
|
||||
* FREQ=MONTHLY;BYDAY=<n><DAY> the n-th <DAY> of the month (n = 1..4 or -1)
|
||||
* FREQ=MONTHLY;BYDAY=<DAY> every <DAY> of the month
|
||||
* FREQ=MONTHLY;BYMONTH=m restrict to month m (1-12)
|
||||
*
|
||||
* BYDAY codes are the RFC 5545 two-letter abbreviations (SU, MO, …, SA).
|
||||
*
|
||||
* DST is NOT handled here — `expandRRULE` returns local dates only. The caller
|
||||
* converts each date to a UTC instant with `localToUtc` (tz.ts), which resolves
|
||||
* the offset for the actual instant, so a 9:00 AM Sunday stays 9:00 AM across
|
||||
* spring-forward / fall-back. This function only decides the calendar date.
|
||||
*
|
||||
* Interval phase (biweekly) is anchored to a fixed epoch (1970-01-04, a
|
||||
* Sunday), so the phase is stable regardless of the window's start — a
|
||||
* biweekly service never drifts week-to-week.
|
||||
*/
|
||||
|
||||
const WEEKDAY_CODES: Record<string, number> = {
|
||||
SU: 0,
|
||||
MO: 1,
|
||||
TU: 2,
|
||||
WE: 3,
|
||||
TH: 4,
|
||||
FR: 5,
|
||||
SA: 6,
|
||||
};
|
||||
|
||||
/** 1970-01-04 — a Sunday. Anchor for interval phase (ARCHITECTURE §5.1). */
|
||||
const INTERVAL_ANCHOR_MS = Date.UTC(1970, 0, 4);
|
||||
|
||||
export interface ByDayRule {
|
||||
/** Weekday (0=Sun..6=Sat) the rule lands on. */
|
||||
weekday: number;
|
||||
/** nth occurrence for MONTHLY: 1..4, -1 (last), or undefined (every). */
|
||||
nth?: number;
|
||||
}
|
||||
|
||||
export interface ParsedRecurrence {
|
||||
freq: "WEEKLY" | "MONTHLY";
|
||||
interval: number;
|
||||
/** Weekday(s) the rule lands on. */
|
||||
byDay: ByDayRule[];
|
||||
/** Restrict MONTHLY to a single month (1-12). */
|
||||
byMonth?: number;
|
||||
/** Explicit day-of-month for MONTHLY (BYMONTHDAY). */
|
||||
byMonthDay?: number;
|
||||
}
|
||||
|
||||
export class RecurrenceError extends Error {
|
||||
constructor(message: string) {
|
||||
super(message);
|
||||
this.name = "RecurrenceError";
|
||||
}
|
||||
}
|
||||
|
||||
/** Parse a rule string into a structured form. Throws `RecurrenceError`. */
|
||||
export function parseRecurrence(rrule: string): ParsedRecurrence {
|
||||
if (typeof rrule !== "string" || rrule.trim() === "") {
|
||||
throw new RecurrenceError("a service needs a recurrence rule");
|
||||
}
|
||||
|
||||
const parsed: ParsedRecurrence = { freq: "WEEKLY", interval: 1, byDay: [] };
|
||||
|
||||
for (const raw of rrule.split(";")) {
|
||||
const part = raw.trim();
|
||||
if (part === "") continue;
|
||||
const eq = part.indexOf("=");
|
||||
if (eq === -1) throw new RecurrenceError(`malformed rule segment: ${part}`);
|
||||
const key = part.slice(0, eq).toUpperCase();
|
||||
const value = part.slice(eq + 1).toUpperCase();
|
||||
|
||||
switch (key) {
|
||||
case "FREQ":
|
||||
if (value === "WEEKLY") {
|
||||
parsed.freq = "WEEKLY";
|
||||
} else if (value === "BIWEEKLY") {
|
||||
// BIWEEKLY is WEEKLY with INTERVAL=2 — normalise to the base form.
|
||||
parsed.freq = "WEEKLY";
|
||||
parsed.interval = 2;
|
||||
} else if (value === "MONTHLY") {
|
||||
parsed.freq = "MONTHLY";
|
||||
} else {
|
||||
throw new RecurrenceError(`unsupported FREQ=${value}`);
|
||||
}
|
||||
break;
|
||||
case "INTERVAL": {
|
||||
const n = Number(value);
|
||||
if (!Number.isInteger(n) || n < 1) {
|
||||
throw new RecurrenceError(`INTERVAL must be a positive integer`);
|
||||
}
|
||||
parsed.interval = n;
|
||||
break;
|
||||
}
|
||||
case "BYDAY":
|
||||
for (const token of value.split(",")) {
|
||||
const rule = parseByDayToken(token.trim());
|
||||
if (rule === null) throw new RecurrenceError(`invalid BYDAY: ${token}`);
|
||||
parsed.byDay.push(rule);
|
||||
}
|
||||
break;
|
||||
case "BYMONTH": {
|
||||
const n = Number(value);
|
||||
if (!Number.isInteger(n) || n < 1 || n > 12) {
|
||||
throw new RecurrenceError(`BYMONTH must be 1-12`);
|
||||
}
|
||||
parsed.byMonth = n;
|
||||
break;
|
||||
}
|
||||
case "BYMONTHDAY": {
|
||||
const n = Number(value);
|
||||
if (!Number.isInteger(n) || n < 1 || n > 31) {
|
||||
throw new RecurrenceError(`BYMONTHDAY must be 1-31`);
|
||||
}
|
||||
parsed.byMonthDay = n;
|
||||
break;
|
||||
}
|
||||
default:
|
||||
throw new RecurrenceError(`unsupported rule component: ${key}`);
|
||||
}
|
||||
}
|
||||
|
||||
// WEEKLY always lands on a weekday; MONTHLY without BYDAY/BYMONTHDAY is
|
||||
// ambiguous and unsupported by this subset.
|
||||
if (parsed.byDay.length === 0) {
|
||||
throw new RecurrenceError("a rule must include BYDAY");
|
||||
}
|
||||
|
||||
return parsed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse an RFC 5545 BYDAY token: "SU" (weekday only), "1SU" (1st Sunday),
|
||||
* "-1WE" (last Wednesday). Returns null when the token is not a valid code.
|
||||
*/
|
||||
function parseByDayToken(token: string): ByDayRule | null {
|
||||
const match = token.match(/^(-?\d+)?([A-Z]{2})$/);
|
||||
if (!match || !(match[2] in WEEKDAY_CODES)) return null;
|
||||
const weekday = WEEKDAY_CODES[match[2]];
|
||||
const nth = match[1] ? parseInt(match[1], 10) : undefined;
|
||||
return { weekday, nth };
|
||||
}
|
||||
|
||||
/** Weeks since the interval anchor, for stable biweekly phase. */
|
||||
function weeksSinceAnchor(dateStr: string): number {
|
||||
const [y, m, d] = dateStr.split("-").map(Number);
|
||||
const ms = Date.UTC(y, m - 1, d);
|
||||
return Math.floor((ms - INTERVAL_ANCHOR_MS) / (7 * 24 * 3600 * 1000));
|
||||
}
|
||||
|
||||
/** Days of `weekday` in a given month, as day-of-month numbers. */
|
||||
function nthWeekdayDays(year: number, month: number, weekday: number, nth?: number): number[] {
|
||||
const daysInMonth = new Date(Date.UTC(year, month, 0)).getUTCDate();
|
||||
const all: number[] = [];
|
||||
for (let day = 1; day <= daysInMonth; day++) {
|
||||
if (new Date(Date.UTC(year, month - 1, day)).getUTCDay() === weekday) all.push(day);
|
||||
}
|
||||
if (nth === undefined) return all;
|
||||
if (nth > 0) return nth <= all.length ? [all[nth - 1]] : [];
|
||||
// nth < 0 counts from the end: -1 is the last occurrence.
|
||||
const idx = all.length + nth;
|
||||
return idx >= 0 ? [all[idx]] : [];
|
||||
}
|
||||
|
||||
/** True if a local date string (YYYY-MM-DD) is on the recurrence. */
|
||||
export function matchesRecurrence(dateStr: string, parsed: ParsedRecurrence): boolean {
|
||||
const [y, m, d] = dateStr.split("-").map(Number);
|
||||
const weekday = new Date(Date.UTC(y, m - 1, d)).getUTCDay();
|
||||
|
||||
if (parsed.freq === "WEEKLY") {
|
||||
if (!parsed.byDay.some((rule) => rule.weekday === weekday)) return false;
|
||||
if (parsed.interval > 1 && weeksSinceAnchor(dateStr) % parsed.interval !== 0) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
// MONTHLY
|
||||
if (parsed.byMonth !== undefined && m !== parsed.byMonth) return false;
|
||||
if (parsed.byMonthDay !== undefined) return d === parsed.byMonthDay;
|
||||
if (parsed.byDay.length === 0) return false;
|
||||
for (const { weekday: code, nth } of parsed.byDay) {
|
||||
if (weekday !== code) continue;
|
||||
if (nth === undefined) return true; // every occurrence of this weekday
|
||||
if (nthWeekdayDays(y, m, code, nth).includes(d)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export interface ExpandOptions {
|
||||
/** Local dates (YYYY-MM-DD) to exclude — one-off cancellations / skips. */
|
||||
skipDates?: ReadonlySet<string>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Expand a rule into every local date in [from, to] (inclusive). Dates are
|
||||
* returned as YYYY-MM-DD strings in the church's local timezone. `skipDates`
|
||||
* removes one-off cancellations so a skipped Sunday is never regenerated.
|
||||
*/
|
||||
export function expandRRULE(
|
||||
rrule: string,
|
||||
from: string,
|
||||
to: string,
|
||||
opts: ExpandOptions = {},
|
||||
): string[] {
|
||||
const parsed = parseRecurrence(rrule);
|
||||
const skip = opts.skipDates;
|
||||
|
||||
const [fy, fm, fd] = from.split("-").map(Number);
|
||||
const [ty, tm, td] = to.split("-").map(Number);
|
||||
const endMs = Date.UTC(ty, tm - 1, td, 23, 59, 59);
|
||||
|
||||
const out: string[] = [];
|
||||
const cursor = new Date(Date.UTC(fy, fm - 1, fd));
|
||||
const startMs = Date.UTC(fy, fm - 1, fd);
|
||||
if (cursor.getTime() < startMs) cursor.setUTCDate(cursor.getUTCDate() + 1);
|
||||
|
||||
while (cursor.getTime() <= endMs) {
|
||||
const ds = toISO(cursor);
|
||||
if (!skip || !skip.has(ds)) {
|
||||
if (matchesRecurrence(ds, parsed)) out.push(ds);
|
||||
}
|
||||
cursor.setUTCDate(cursor.getUTCDate() + 1);
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Validate a rule, returning human-readable problems (empty when valid). */
|
||||
export function validateRecurrence(rrule: string): string[] {
|
||||
try {
|
||||
parseRecurrence(rrule);
|
||||
return [];
|
||||
} catch (err) {
|
||||
return [err instanceof RecurrenceError ? err.message : "invalid recurrence rule"];
|
||||
}
|
||||
}
|
||||
|
||||
function toISO(d: Date): string {
|
||||
const y = d.getUTCFullYear();
|
||||
const m = String(d.getUTCMonth() + 1).padStart(2, "0");
|
||||
const day = String(d.getUTCDate()).padStart(2, "0");
|
||||
return `${y}-${m}-${day}`;
|
||||
}
|
||||
Reference in New Issue
Block a user