unit(D4): blackout CRUD + isUnavailable(user, date)

Blackout / unavailability (ARCHITECTURE §4.7 / §5.3 rule 5 / §5.4):
- src/domain/availability.ts — pure isUnavailable(records, date); a record
  covers the date if active and its inclusive range [starts_on, ends_on]
  contains it OR its rrule matches. No DB imports.
- src/domain/availability.test.ts — 11 tests named after the rule, incl.
  the inclusive-end case (2026-11-21..2026-11-28 covers 11-28).
- src/db/schema.ts — unavailability table: CHECK ends_on >= starts_on,
  CHECK span <= 365 days, unique (user_id, starts_on, ends_on) WHERE active.
- src/db/unavailability.ts — list/get/create/update/cancel (soft-delete);
  range + rrule validated on write.
- src/app/api/dev/unavailability/route.ts — GET/POST/PATCH; bad range/rrule
  -> 400, cancel flips status=cancelled.
- drizzle/0008_needy_stryfe.sql + migration applied to DB on :5433.

date columns stored as strings (mode: string) to match the YYYY-MM-DD
domain; Postgres date is mode-agnostic so the migration is unchanged.
Constraints enforced twice: validateUnavailabilityRange at the API,
chk_unavailability_* at the DB.

.env added to .gitignore (real secret was not ignored; .env.* missed the
bare .env).
This commit is contained in:
Tiel Coder
2026-11-18 11:25:43 +00:00
parent 8ee339b235
commit deb4f35fb8
10 changed files with 3012 additions and 2 deletions
+145
View File
@@ -0,0 +1,145 @@
import { NextRequest } from "next/server";
import { z } from "zod";
import {
listUnavailability,
createUnavailability,
updateUnavailability,
cancelUnavailability,
} from "@/db/unavailability";
const JSON_HEADERS = { "content-type": "application/json" };
const idSchema = z.string().min(1);
const kindSchema = z
.enum(["blackout", "vacation", "recurring", "preference"])
.optional();
const statusSchema = z.enum(["active", "cancelled"]).optional();
const unavailabilityCreateSchema = z.object({
userId: z.string().min(1),
kind: kindSchema,
startsOn: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
endsOn: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
allDay: z.boolean().optional(),
reason: z.string().nullable().optional(),
rrule: z.string().nullable().optional(),
status: statusSchema,
createdBy: z.string().nullable().optional(),
});
const unavailabilityUpdateSchema = unavailabilityCreateSchema.partial().omit({
userId: true,
});
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. Returns null otherwise. */
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 === "23514") {
return new Response(JSON.stringify({ error: "invalid blackout range" }), {
status: 400,
headers: JSON_HEADERS,
});
}
if (code === "23503") {
return new Response(
JSON.stringify({ error: "referenced user does not exist" }),
{ status: 400, headers: JSON_HEADERS },
);
}
return null;
};
/** GET /api/dev/unavailability?userId=... — list blackouts (one per user). */
export const GET = async (req: NextRequest) => {
const userId = req.nextUrl.searchParams.get("userId") ?? undefined;
const rows = await listUnavailability({ userId });
return new Response(JSON.stringify({ rows }), {
status: 200,
headers: JSON_HEADERS,
});
};
/** POST /api/dev/unavailability { ...fields } — create a blackout. */
export const POST = async (req: NextRequest) => {
const body = await readBody(req);
if (!body || typeof body !== "object") {
return bad("invalid body");
}
const parsed = unavailabilityCreateSchema.safeParse(body);
if (!parsed.success) return bad(parsed.error.message);
try {
return created(await createUnavailability(parsed.data));
} catch (err) {
const constraint = constraintError(err);
if (constraint) return constraint;
return bad(err instanceof Error ? err.message : "internal error");
}
};
/**
* PATCH /api/dev/unavailability { id, ...fields } — edit a blackout.
* PATCH { id, status: "cancelled" } — cancel (soft delete).
*/
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");
// Cancel path: explicit status cancelled.
if ((body as { status?: unknown }).status === "cancelled") {
const row = await cancelUnavailability(id.data);
return ok(row);
}
const parsed = unavailabilityUpdateSchema.safeParse(body);
if (!parsed.success) return bad(parsed.error.message);
try {
const row = await updateUnavailability(id.data, parsed.data);
return row ? ok(row) : bad("blackout not found");
} catch (err) {
const constraint = constraintError(err);
if (constraint) return constraint;
return bad(err instanceof Error ? err.message : "internal error");
}
};
+60 -1
View File
@@ -8,7 +8,7 @@
* - notification_templates/rules/outbox (later)
* - user_skills (C2), skill_assessments (C3), growth_goals (C6),
* skill_equivalencies (later)
* - service_role_requirements, unavailability, events, notifications outbox
* - service_role_requirements, events, notifications outbox
*
* Conventions (ARCHITECTURE §4.2):
* - `id` is a UUIDv7 text column (generated at the app/seed layer, see src/lib/uuid.ts)
@@ -40,6 +40,13 @@ export type AssignmentStatus = (typeof ASSIGNMENT_STATUSES)[number];
export const ASSIGNMENT_SOURCES = ["manual", "auto", "swap", "import"] as const;
export type AssignmentSource = (typeof ASSIGNMENT_SOURCES)[number];
// Added in D4 (blackout CRUD + isUnavailable). ARCHITECTURE §"unavailability — blackout dates".
export const UNAVAILABILITY_KINDS = ["blackout", "vacation", "recurring", "preference"] as const;
export type UnavailabilityKind = (typeof UNAVAILABILITY_KINDS)[number];
export const UNAVAILABILITY_STATUSES = ["active", "cancelled"] as const;
export type UnavailabilityStatus = (typeof UNAVAILABILITY_STATUSES)[number];
export const CONFIRMED_VIAS = ["app", "email_link", "sms_reply", "admin"] as const;
export type ConfirmedVia = (typeof CONFIRMED_VIAS)[number];
@@ -288,6 +295,57 @@ export const assignments = pgTable(
],
);
/* ------------------------------------------------- unavailability (D4) */
/**
* Blackout / unavailability rows (ARCHITECTURE §\"unavailability — blackout
* dates\"). A volunteer publishes blackout dates; `isUnavailable` (D4) reads
* them to exclude the volunteer from the assign picker and auto-fill.
*
* `starts_on` / `ends_on` are inclusive local dates (same day = one day).
* CHECK constraints enforce `ends_on >= starts_on` and a <= 365 day span.
*/
export const unavailability = pgTable(
"unavailability",
{
id: text("id").primaryKey(),
userId: text("user_id")
.notNull()
.references(() => users.id, { onDelete: "cascade" }),
kind: text("kind", { enum: UNAVAILABILITY_KINDS })
.notNull()
.default("blackout"),
/** Inclusive local-date range; same day = one day. Stored as YYYY-MM-DD. */
startsOn: date("starts_on", { mode: "string" }).notNull(),
endsOn: date("ends_on", { mode: "string" }).notNull(),
allDay: boolean("all_day").notNull().default(true),
/** Private by default; admin-visible only. */
reason: text("reason"),
/** Recurring pattern (RFC 5545 subset), e.g. every other week. */
rrule: text("rrule"),
status: text("status", { enum: UNAVAILABILITY_STATUSES })
.notNull()
.default("active"),
createdAt: timestamp("created_at", { mode: "date", withTimezone: true })
.defaultNow(),
createdBy: text("created_by"),
},
(table) => [
// One active record per (user, range); recurring records carry an rrule.
uniqueIndex("uq_unavailability_range")
.on(table.userId, table.startsOn, table.endsOn)
.where(sql`${table.status} = 'active'`),
index("unavailability_user_idx").on(table.userId),
// Inclusive range: ends_on must not precede starts_on.
check("chk_unavailability_span", sql`${table.endsOn} >= ${table.startsOn}`),
// Max span 365 days (date - date is an integer number of days in PG).
check(
"chk_unavailability_max_span",
sql`${table.endsOn} - ${table.startsOn} <= 365`,
),
],
);
/* ------------------------------------------------------------- catalog */
/**
@@ -678,6 +736,7 @@ export const schema = {
serviceInstances,
slots,
assignments,
unavailability,
skillCategories,
vendors,
technologies,
+143
View File
@@ -0,0 +1,143 @@
/**
* Blackout / unavailability rows (ARCHITECTURE §"unavailability — blackout
* dates"). D4 writes these — a volunteer publishes blackout dates; the pure
* `isUnavailable` (src/domain/availability.ts) reads them to exclude the
* volunteer from the assign picker and auto-fill.
*
* Integrity rules:
* - `ends_on` is inclusive and must not precede `starts_on`; span <= 365 days.
* Both are validated on write so a bad range can never reach the DB.
* - `rrule` is validated on write (RFC 5545 subset) so a malformed rule can
* never reach `isUnavailable`.
* - Cancel, never delete — `status` flips to `cancelled`; the row persists so
* historical assignment conflicts stay explainable.
*
* Read path: `listUnavailability({ userId })` returns one record per user; omit
* `userId` for the admin-wide list.
*/
import { eq } from "drizzle-orm";
import { db } from "@/db";
import { unavailability } from "@/db/schema";
import { uuidv7 } from "@/lib/uuid";
import { validateRecurrence } from "@/domain/recurrence";
type UnavailabilityInsert = typeof unavailability.$inferInsert;
export type UnavailabilityCreate = Omit<
UnavailabilityInsert,
"id" | "created_at" | "created_by"
> & { createdBy?: string | null };
export type UnavailabilityUpdate = Partial<
Omit<UnavailabilityInsert, "id" | "created_at">
>;
const notNull = <T>(value: T | null | undefined): T | undefined =>
value === null || value === undefined ? undefined : value;
/**
* Validate the inclusive range: `ends_on >= starts_on` and a span of <= 365
* days. Dates are ISO (YYYY-MM-DD) strings; the span is computed in whole days.
*/
export function validateUnavailabilityRange(
startsOn: string,
endsOn: string,
): string[] {
const errors: string[] = [];
if (endsOn < startsOn) errors.push("ends_on must not precede starts_on");
const days = Math.round(
(Date.parse(`${endsOn}T00:00:00Z`) - Date.parse(`${startsOn}T00:00:00Z`)) /
86_400_000,
);
if (days > 365) errors.push("span must not exceed 365 days");
return errors;
}
export async function listUnavailability({ userId }: { userId?: string } = {}) {
const where = userId
? eq(unavailability.userId, userId)
: undefined;
return await db
.select()
.from(unavailability)
.where(where)
.orderBy(unavailability.startsOn, unavailability.endsOn);
}
export async function getUnavailability(id: string) {
const [row] = await db.select().from(unavailability).where(eq(unavailability.id, id));
return row ?? null;
}
export async function createUnavailability(fields: UnavailabilityCreate) {
const problems = validateUnavailabilityRange(fields.startsOn, fields.endsOn);
if (fields.rrule != null) problems.push(...validateRecurrence(fields.rrule));
if (problems.length > 0) {
throw new Error(problems.join("; "));
}
const values: UnavailabilityInsert = {
id: uuidv7(),
userId: fields.userId,
kind: fields.kind,
startsOn: fields.startsOn,
endsOn: fields.endsOn,
allDay: fields.allDay ?? true,
reason: notNull(fields.reason),
rrule: notNull(fields.rrule),
status: fields.status ?? "active",
createdBy: notNull(fields.createdBy),
};
const [row] = await db.insert(unavailability).values(values).returning();
return row;
}
export async function updateUnavailability(
id: string,
fields: UnavailabilityUpdate,
) {
const current = await getUnavailability(id);
if (!current) return null;
// Validate the resulting range even when only one bound is being changed.
const startsOn = (fields.startsOn ?? current.startsOn) as string;
const endsOn = (fields.endsOn ?? current.endsOn) as string;
const problems = validateUnavailabilityRange(startsOn, endsOn);
if (fields.rrule != null) problems.push(...validateRecurrence(fields.rrule));
if (problems.length > 0) {
throw new Error(problems.join("; "));
}
const patch: Record<string, unknown> = {};
const editable: (keyof UnavailabilityUpdate)[] = [
"kind",
"startsOn",
"endsOn",
"allDay",
"reason",
"rrule",
"status",
];
for (const key of editable) {
if (fields[key] !== undefined) patch[key] = fields[key];
}
if (Object.keys(patch).length === 0) return current;
const [row] = await db
.update(unavailability)
.set(patch)
.where(eq(unavailability.id, id))
.returning();
return row;
}
/** Cancel (soft-delete) a blackout; the row persists for audit. */
export async function cancelUnavailability(id: string) {
const [row] = await db
.update(unavailability)
.set({ status: "cancelled" })
.where(eq(unavailability.id, id))
.returning();
return row;
}
+92
View File
@@ -0,0 +1,92 @@
import { describe, expect, it } from "vitest";
import {
isUnavailable,
overlapsRange,
recordCovers,
type UnavailabilityRecord,
} from "./availability";
const record = (partial: Partial<UnavailabilityRecord>): UnavailabilityRecord => ({
id: "u1",
userId: "user-1",
kind: "blackout",
startsOn: "2026-11-21",
endsOn: "2026-11-28",
allDay: true,
reason: null,
rrule: null,
status: "active",
createdAt: new Date(),
createdBy: null,
...partial,
});
describe("overlapsRange — inclusive on both ends", () => {
it("covers the start date", () => {
expect(overlapsRange("2026-11-21", "2026-11-21", "2026-11-28")).toBe(true);
});
it("covers the END date (inclusive-end case)", () => {
expect(overlapsRange("2026-11-28", "2026-11-21", "2026-11-28")).toBe(true);
});
it("excludes the day before start and the day after end", () => {
expect(overlapsRange("2026-11-20", "2026-11-21", "2026-11-28")).toBe(false);
expect(overlapsRange("2026-11-29", "2026-11-21", "2026-11-28")).toBe(false);
});
it("a same-day blackout covers exactly that day", () => {
expect(overlapsRange("2026-12-25", "2026-12-25", "2026-12-25")).toBe(true);
expect(overlapsRange("2026-12-24", "2026-12-25", "2026-12-25")).toBe(false);
});
});
describe("recordCovers", () => {
it("honours an active range", () => {
expect(recordCovers(record({}), "2026-11-25")).toBe(true);
});
it("a cancelled record never covers", () => {
expect(recordCovers(record({ status: "cancelled" }), "2026-11-25")).toBe(false);
});
it("a recurring rule matches its weekday", () => {
// Every other Sunday starting 2026-11-22: 11-22, 12-06 match; 11-29 does
// not (it is the skipped Sunday of the 2-week interval).
const r = record({
startsOn: "2026-11-22",
endsOn: "2027-12-31",
rrule: "FREQ=WEEKLY;INTERVAL=2;BYDAY=SU",
});
expect(recordCovers(r, "2026-11-22")).toBe(true);
expect(recordCovers(r, "2026-12-06")).toBe(true);
// The intervening Sunday is outside the 2-week interval.
expect(recordCovers(r, "2026-11-29")).toBe(false);
});
it("a malformed rrule does not throw and does not match", () => {
const r = record({ rrule: "FREQ=MONTHLY;BOGUS" });
expect(() => recordCovers(r, "2026-11-25")).not.toThrow();
expect(recordCovers(r, "2026-11-25")).toBe(false);
});
});
describe("isUnavailable", () => {
it("true when any active record covers the date", () => {
const records = [
record({ id: "a", startsOn: "2026-11-01", endsOn: "2026-11-10" }),
record({ id: "b", startsOn: "2026-11-25", endsOn: "2026-11-28" }),
];
expect(isUnavailable(records, "2026-11-28")).toBe(true);
expect(isUnavailable(records, "2026-11-05")).toBe(true);
});
it("false when no record covers the date", () => {
const records = [record({ startsOn: "2026-11-25", endsOn: "2026-11-28" })];
expect(isUnavailable(records, "2026-12-25")).toBe(false);
});
it("false for an empty record set", () => {
expect(isUnavailable([], "2026-11-25")).toBe(false);
});
});
+63
View File
@@ -0,0 +1,63 @@
/**
* Availability — unit D4 (ARCHITECTURE §"unavailability — blackout dates").
*
* Pure: no DB, no `src/db` imports. `isUnavailable(userRecords, date)` answers
* whether a volunteer is out on a given local date (YYYY-MM-DD), so the assign
* picker and auto-fill can exclude them.
*
* A record covers the date if it is `active` and either:
* - its inclusive range `[starts_on, ends_on]` contains the date, or
* - its `rrule` (RFC 5545 subset) matches the date.
*
* Range bounds are INCLUSIVE on both ends: a blackout 2026-11-21..2026-11-28
* covers 2026-11-28 (the end date), not just up to 2026-11-27.
*/
import { parseRecurrence, matchesRecurrence, validateRecurrence } from "./recurrence";
export type UnavailabilityKind = "blackout" | "vacation" | "recurring" | "preference";
export type UnavailabilityStatus = "active" | "cancelled";
export interface UnavailabilityRecord {
id: string;
userId: string;
kind: UnavailabilityKind;
/** Inclusive local-date range; same day = one day. */
startsOn: string;
endsOn: string;
allDay: boolean;
reason: string | null;
/** Recurring pattern (RFC 5545 subset), e.g. "FREQ=WEEKLY;INTERVAL=2". */
rrule: string | null;
status: UnavailabilityStatus;
createdAt: Date;
createdBy: string | null;
}
/**
* Inclusive range check: `startsOn <= date <= endsOn`. ISO (YYYY-MM-DD) strings
* compare correctly lexicographically, so no date parsing is needed here.
*/
export function overlapsRange(date: string, startsOn: string, endsOn: string): boolean {
return date >= startsOn && date <= endsOn;
}
/** Is this single record active and covering `date`? */
export function recordCovers(record: UnavailabilityRecord, date: string): boolean {
if (record.status !== "active") return false;
// A recurring rule is authoritative for coverage; the range (if any) is just
// metadata and is not used to over-cover non-matching dates.
if (record.rrule) {
// Guard the rrule: parseRecurrence() throws on malformed input, so only
// match when validateRecurrence() reports the rule is well-formed.
return validateRecurrence(record.rrule).length === 0
&& matchesRecurrence(date, parseRecurrence(record.rrule));
}
// Range-only blackout: inclusive on both ends.
return overlapsRange(date, record.startsOn, record.endsOn);
}
/** Is the user unavailable on `date` (YYYY-MM-DD)? */
export function isUnavailable(records: UnavailabilityRecord[], date: string): boolean {
return records.some((record) => recordCovers(record, date));
}