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:
@@ -445,3 +445,27 @@ Build log for Media Team Hub. One unit per commit, top to bottom. Append after e
|
|||||||
- **Removed `.freebuff/`.** A root-owned local tooling dir (`project-id`, gitignored) that blocked `eslint .` (the `pnpm lint` DoD gate) — `drizzle`/ESLint could not scandir it. It held only a local project id; removed with `sudo rm -rf` and its `.git/info/exclude` entry cleared, restoring a clean `eslint .`.
|
- **Removed `.freebuff/`.** A root-owned local tooling dir (`project-id`, gitignored) that blocked `eslint .` (the `pnpm lint` DoD gate) — `drizzle`/ESLint could not scandir it. It held only a local project id; removed with `sudo rm -rf` and its `.git/info/exclude` entry cleared, restoring a clean `eslint .`.
|
||||||
|
|
||||||
**Next: D1 — service CRUD + `expandRRULE()` (weekly / biweekly / monthly-nth).**
|
**Next: D1 — service CRUD + `expandRRULE()` (weekly / biweekly / monthly-nth).**
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## D1 — Service CRUD + `expandRRULE()` — DONE 2026-11-18
|
||||||
|
|
||||||
|
**Scope (from BUILD-PLAN.md):** service CRUD + `expandRRULE()` (weekly / biweekly / monthly-nth). Done when: `pnpm test recurrence` green on 5 named cases — spring-forward Sunday, fall-back Sunday, monthly-nth across a year boundary, cancelled instance not regenerated, biweekly phase stable. ARCHITECTURE §4.3 / §5.1 / §5.8.3.
|
||||||
|
|
||||||
|
**Delivered:**
|
||||||
|
- `src/domain/recurrence.ts` — `expandRRULE(rrule, from, to, { skipDates })` returns the local dates a rule lands on in a window. Parses the RFC 5545 subset: `FREQ=WEEKLY` (with `INTERVAL=n`, so `INTERVAL=2` = biweekly), `FREQ=MONTHLY;BYDAY=<n><DAY>` (nth weekday, incl. `-1` = last) and `BYMONTH`. `parseRecurrence`, `matchesRecurrence`, `validateRecurrence`, `RecurrenceError`. Pure — no DB imports.
|
||||||
|
- `src/domain/recurrence.test.ts` — 13 tests named after the rule. The 5 required cases: spring-forward Sunday (9 AM local stays 9 AM; stored UTC shifts EST→EDT), fall-back Sunday (UTC shifts back), monthly-nth across Dec→Jan (1st Sunday), cancelled instance not regenerated (skip date excluded), biweekly phase stable (constant 14-day gap). Plus INTERVAL=3, last-weekday, parse/validate.
|
||||||
|
- `src/db/services.ts` — `listServices({ active })`, `getService`, `createService`, `updateService`, `deactivateService`. `rrule` validated on write; deactivate flips `active` (never delete); `name` frozen on update.
|
||||||
|
- `src/app/api/dev/services/route.ts` — GET (list, `active` filter), POST (create, 409 on duplicate name), PATCH (edit fields or `active:false` deactivate). Constraint errors mapped to 400/409 like the catalog route.
|
||||||
|
|
||||||
|
**No schema change, no migration.** The `services` table already exists (A2) with all fields (`rrule`, `startTime_local`, `duration_minutes`, `doors_open_minutes_before`, `active`, `notes`). D1 owns the template CRUD; `service_role_requirements` stays deferred to a later unit.
|
||||||
|
|
||||||
|
**Verification (all exit 0):**
|
||||||
|
- `tsc --noEmit` ✓ · `eslint .` ✓ · `vitest run src/domain/recurrence.test.ts` ✓ (**13**) · `next build` ✓ · runtime smoke test: GET/POST/PATCH all correct, DB persistence confirmed (deactivate flips `active=false`, duration update persisted, duplicate name → 409, invalid rrule → 400).
|
||||||
|
|
||||||
|
**Decisions:**
|
||||||
|
- **`expandRRULE` returns local dates; DST lives in the caller.** The function decides the calendar date only; the instance generator (D2) converts each with `localToUtc`, which resolves the offset for the actual instant — so a 9 AM Sunday stays 9 AM across spring-forward / fall-back. The DST tests assert the stored UTC hour shifts by an hour across the transition.
|
||||||
|
- **Interval phase anchored to 1970-01-04 (a Sunday).** Without a DTSTART, biweekly/triweekly phase is computed against a fixed epoch, so the phase never drifts week-to-week regardless of the window start.
|
||||||
|
- **nth weekday parsed from the BYDAY token.** `1SU` / `-1WE` carry the position in the token (`ByDayRule.weekday` + `.nth`); `BYSETPOS` was dropped as redundant — the app's "1st Sunday" maps to `BYDAY=1SU`.
|
||||||
|
- **`rrule` validated on write.** A malformed rule can never reach the generator; `createService`/`updateService` call `validateRecurrence` and reject with a 400 message before touching the DB.
|
||||||
|
- **Build cache reclaimed.** A prior interrupted `next build` left root-owned files under `.next/` (same class as the earlier `.git/objects` scrub) that blocked rebuilds; `sudo chown -R bhursey:bhursey .next` restored the build. The stale `next start` on :3000 was restarted after the build so the new route loaded.
|
||||||
|
|||||||
@@ -0,0 +1,141 @@
|
|||||||
|
import { NextRequest } from "next/server";
|
||||||
|
import { z } from "zod";
|
||||||
|
import {
|
||||||
|
listServices,
|
||||||
|
createService,
|
||||||
|
updateService,
|
||||||
|
deactivateService,
|
||||||
|
} from "@/db/services";
|
||||||
|
|
||||||
|
const JSON_HEADERS = { "content-type": "application/json" };
|
||||||
|
|
||||||
|
const idSchema = z.string().min(1);
|
||||||
|
|
||||||
|
const serviceCreateSchema = z.object({
|
||||||
|
name: z.string().min(1),
|
||||||
|
location: z.string().nullable().optional(),
|
||||||
|
timezone: z.string().optional(),
|
||||||
|
rrule: z.string().nullable().optional(),
|
||||||
|
startTimeLocal: z.string().min(1),
|
||||||
|
durationMinutes: z.number().int().min(1).optional(),
|
||||||
|
doorsOpenMinutesBefore: z.number().int().min(0).optional(),
|
||||||
|
notes: z.string().nullable().optional(),
|
||||||
|
active: z.boolean().optional(),
|
||||||
|
});
|
||||||
|
|
||||||
|
const serviceUpdateSchema = serviceCreateSchema.partial();
|
||||||
|
|
||||||
|
async function readBody(req: NextRequest) {
|
||||||
|
try {
|
||||||
|
return await req.json();
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const bad = (message: string) =>
|
||||||
|
new Response(JSON.stringify({ error: message }), {
|
||||||
|
status: 400,
|
||||||
|
headers: JSON_HEADERS,
|
||||||
|
});
|
||||||
|
|
||||||
|
const ok = (row: unknown) =>
|
||||||
|
new Response(JSON.stringify({ row }), {
|
||||||
|
status: 200,
|
||||||
|
headers: JSON_HEADERS,
|
||||||
|
});
|
||||||
|
|
||||||
|
const created = (row: unknown) =>
|
||||||
|
new Response(JSON.stringify({ row }), {
|
||||||
|
status: 201,
|
||||||
|
headers: JSON_HEADERS,
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Map Postgres constraint violations to client errors (see catalog route).
|
||||||
|
* Returns null for non-constraint errors so callers can apply their own message.
|
||||||
|
*/
|
||||||
|
const constraintError = (err: unknown): Response | null => {
|
||||||
|
let code: string | undefined;
|
||||||
|
let node: { code?: string; cause?: unknown } | null = err as {
|
||||||
|
code?: string;
|
||||||
|
cause?: unknown;
|
||||||
|
} | null;
|
||||||
|
while (node) {
|
||||||
|
if (node.code) {
|
||||||
|
code = node.code;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
node = (node.cause as { code?: string; cause?: unknown } | null) ?? null;
|
||||||
|
}
|
||||||
|
if (code === "23505") {
|
||||||
|
return new Response(
|
||||||
|
JSON.stringify({ error: "a service with this name already exists" }),
|
||||||
|
{ status: 409, headers: JSON_HEADERS },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (code === "23503" || code === "23514") {
|
||||||
|
return new Response(JSON.stringify({ error: "referenced row does not exist" }), {
|
||||||
|
status: 400,
|
||||||
|
headers: JSON_HEADERS,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** GET /api/dev/services?active=true — list service templates. */
|
||||||
|
export const GET = async (req: NextRequest) => {
|
||||||
|
const active = req.nextUrl.searchParams.get("active") !== "false";
|
||||||
|
const rows = await listServices({ active });
|
||||||
|
return new Response(JSON.stringify({ rows }), {
|
||||||
|
status: 200,
|
||||||
|
headers: JSON_HEADERS,
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
/** POST /api/dev/services { ...fields } — create a service template. */
|
||||||
|
export const POST = async (req: NextRequest) => {
|
||||||
|
const body = await readBody(req);
|
||||||
|
if (!body || typeof body !== "object") {
|
||||||
|
return bad("invalid body");
|
||||||
|
}
|
||||||
|
const parsed = serviceCreateSchema.safeParse(body);
|
||||||
|
if (!parsed.success) return bad(parsed.error.message);
|
||||||
|
try {
|
||||||
|
return created(await createService(parsed.data));
|
||||||
|
} catch (err) {
|
||||||
|
const constraint = constraintError(err);
|
||||||
|
if (constraint) return constraint;
|
||||||
|
return bad(err instanceof Error ? err.message : "internal error");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* PATCH /api/dev/services { id, ...fields } — edit.
|
||||||
|
* PATCH { id, active: false } — deactivate (soft delete).
|
||||||
|
* `name` is never accepted here: it freezes after creation.
|
||||||
|
*/
|
||||||
|
export const PATCH = async (req: NextRequest) => {
|
||||||
|
const body = await readBody(req);
|
||||||
|
if (!body || typeof body !== "object") {
|
||||||
|
return bad("invalid body");
|
||||||
|
}
|
||||||
|
const id = idSchema.safeParse((body as { id?: unknown }).id);
|
||||||
|
if (!id.success) return bad("invalid id");
|
||||||
|
|
||||||
|
// Deactivate path: explicit active=false, no editable fields applied.
|
||||||
|
if ((body as { active?: unknown }).active === false) {
|
||||||
|
const row = await deactivateService(id.data);
|
||||||
|
return ok(row);
|
||||||
|
}
|
||||||
|
|
||||||
|
const parsed = serviceUpdateSchema.safeParse(body);
|
||||||
|
if (!parsed.success) return bad(parsed.error.message);
|
||||||
|
try {
|
||||||
|
return ok(await updateService(id.data, parsed.data));
|
||||||
|
} catch (err) {
|
||||||
|
const constraint = constraintError(err);
|
||||||
|
if (constraint) return constraint;
|
||||||
|
return bad(err instanceof Error ? err.message : "internal error");
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
/**
|
||||||
|
* Service templates (ARCHITECTURE §4.3). D1 writes these — the recurring
|
||||||
|
* gathering template that instances (D2) and slots (D3) are built from.
|
||||||
|
*
|
||||||
|
* Integrity rules:
|
||||||
|
* - Deactivate, never delete — `active` flips to false; the row persists so
|
||||||
|
* historical instances and their assignments are preserved.
|
||||||
|
* - `rrule` is validated on write (RFC 5545 subset) so a malformed rule can
|
||||||
|
* never reach the instance generator.
|
||||||
|
* - `name` is unique and frozen on update (no update path accepts it).
|
||||||
|
*
|
||||||
|
* Read path: `listServices({ active: true })` returns only rows shown in the
|
||||||
|
* admin services list; `active: false` returns the full set (audit).
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { eq } from "drizzle-orm";
|
||||||
|
import { db } from "@/db";
|
||||||
|
import { services } from "@/db/schema";
|
||||||
|
import { uuidv7 } from "@/lib/uuid";
|
||||||
|
import { validateRecurrence } from "@/domain/recurrence";
|
||||||
|
|
||||||
|
type ServiceInsert = typeof services.$inferInsert;
|
||||||
|
|
||||||
|
export type ServiceCreate = Omit<ServiceInsert, "id" | "active"> & { active?: boolean };
|
||||||
|
export type ServiceUpdate = Partial<Omit<ServiceInsert, "id" | "active">>;
|
||||||
|
|
||||||
|
const notNull = <T>(value: T | null | undefined): T | undefined =>
|
||||||
|
value === null || value === undefined ? undefined : value;
|
||||||
|
|
||||||
|
export async function listServices({ active }: { active?: boolean }) {
|
||||||
|
const rows = await db
|
||||||
|
.select()
|
||||||
|
.from(services)
|
||||||
|
.where(active === false ? undefined : eq(services.active, active ?? true))
|
||||||
|
.orderBy(services.name);
|
||||||
|
return rows;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getService(id: string) {
|
||||||
|
const [row] = await db.select().from(services).where(eq(services.id, id));
|
||||||
|
return row ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function createService(fields: ServiceCreate) {
|
||||||
|
const problems = validateRecurrence(fields.rrule ?? "");
|
||||||
|
if (fields.rrule != null && problems.length > 0) {
|
||||||
|
throw new Error(`invalid recurrence: ${problems.join("; ")}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const values: ServiceInsert = {
|
||||||
|
id: uuidv7(),
|
||||||
|
name: fields.name,
|
||||||
|
location: notNull(fields.location),
|
||||||
|
timezone: notNull(fields.timezone),
|
||||||
|
rrule: notNull(fields.rrule),
|
||||||
|
startTimeLocal: fields.startTimeLocal,
|
||||||
|
durationMinutes: notNull(fields.durationMinutes),
|
||||||
|
doorsOpenMinutesBefore: notNull(fields.doorsOpenMinutesBefore),
|
||||||
|
notes: notNull(fields.notes),
|
||||||
|
active: fields.active ?? true,
|
||||||
|
};
|
||||||
|
|
||||||
|
const [row] = await db.insert(services).values(values).returning();
|
||||||
|
return row;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function updateService(id: string, fields: ServiceUpdate) {
|
||||||
|
// A recurrence change is validated before it is written so a bad rule never
|
||||||
|
// reaches the generator.
|
||||||
|
if (fields.rrule != null) {
|
||||||
|
const problems = validateRecurrence(fields.rrule);
|
||||||
|
if (problems.length > 0) {
|
||||||
|
throw new Error(`invalid recurrence: ${problems.join("; ")}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const patch: Record<string, unknown> = {};
|
||||||
|
const editable: (keyof ServiceUpdate)[] = [
|
||||||
|
"location",
|
||||||
|
"timezone",
|
||||||
|
"rrule",
|
||||||
|
"startTimeLocal",
|
||||||
|
"durationMinutes",
|
||||||
|
"doorsOpenMinutesBefore",
|
||||||
|
"notes",
|
||||||
|
];
|
||||||
|
for (const key of editable) {
|
||||||
|
if (fields[key] !== undefined) patch[key] = fields[key];
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Object.keys(patch).length === 0) return await getService(id);
|
||||||
|
|
||||||
|
const [row] = await db.update(services).set(patch).where(eq(services.id, id)).returning();
|
||||||
|
return row;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function deactivateService(id: string) {
|
||||||
|
const [row] = await db
|
||||||
|
.update(services)
|
||||||
|
.set({ active: false })
|
||||||
|
.where(eq(services.id, id))
|
||||||
|
.returning();
|
||||||
|
return row;
|
||||||
|
}
|
||||||
@@ -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