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:
+25
-1
@@ -498,7 +498,31 @@ Build log for Media Team Hub. One unit per commit, top to bottom. Append after e
|
||||
- **Headcount clamped to >= 1.** A role always produces at least one seat, so a zero/missing headcount can never silently drop a role from an instance.
|
||||
- **Seed is date-dependent, not fully idempotent.** The seed materializes `nextSundaysInTz(2)` (rolling window), so re-running it across dates creates new instances. After testing I reset instances/slots/assignments and re-ran the seed once to restore the canonical 4-instance / 12-slot state.
|
||||
|
||||
**Next: D4 — blackout CRUD + `isUnavailable(user, date)` pure function, ranges + rrule.**
|
||||
## D4 — Blackout CRUD + `isUnavailable(user, date)` — DONE 2026-11-18
|
||||
|
||||
**Scope (from BUILD-PLAN.md):** blackout CRUD + `isUnavailable(user, date)` pure function, ranges + rrule. Done when: `pnpm test availability` green incl. inclusive-end case. ARCHITECTURE §4.7 / §5.3 rule 5 / §5.4.
|
||||
|
||||
**Delivered:**
|
||||
- `src/domain/availability.ts` — pure `isUnavailable(records, date)` + `overlapsRange(date, startsOn, endsOn)` + `recordCovers(record, date)`. A record covers the date if it is `active` and either its inclusive range `[starts_on, ends_on]` contains the date (same day = one day) or its `rrule` matches. No DB imports.
|
||||
- `src/domain/availability.test.ts` — 11 tests named after the rule: inclusive-end case (2026-11-21..2026-11-28 covers 11-28), inclusive-start, day-before/day-after excluded, same-day blackout, active range covers, cancelled never covers, recurring rule matches its weekday, intervening Sunday excluded (2-week interval), malformed rrule neither throws nor matches, empty set false.
|
||||
- `src/db/schema.ts` — `unavailability` table (ARCHITECTURE §4.7): `id, user_id (FK users, cascade), kind (enum), starts_on, ends_on (date), all_day (default true), reason (nullable), rrule (nullable), status (enum active|cancelled), created_at, created_by`. CHECK `ends_on >= starts_on`, CHECK `(ends_on - starts_on) <= 365`, unique index `(user_id, starts_on, ends_on) WHERE status='active'`, index on `user_id`.
|
||||
- `src/db/unavailability.ts` — `listUnavailability({ userId })`, `getUnavailability`, `createUnavailability`, `updateUnavailability`, `cancelUnavailability` (soft-delete → `status='cancelled'`). Range validated on write (`validateUnavailabilityRange`); `rrule` validated via `validateRecurrence`.
|
||||
- `src/app/api/dev/unavailability/route.ts` — GET (list, `userId` filter), POST (create, 400 on bad range/rrule), PATCH (edit or `status:'cancelled'` cancel). Constraint errors mapped to 400.
|
||||
|
||||
**Schema change + migration:** `drizzle/0008_needy_stryfe.sql` creates the `unavailability` table. Applied to the DB on :5433.
|
||||
|
||||
**Verification (all exit 0):**
|
||||
- `tsc --noEmit` ✓ · `eslint .` ✓ (0 problems) · `vitest run` ✓ (**140** total; D4 = 11)
|
||||
- Runtime smoke test (running app on :3000): POST valid blackout → 201; POST span > 365 → 400 "span must not exceed 365 days"; POST ends < starts → 400 "ends_on must not precede starts_on"; GET list; PATCH cancel → 200 with `status='cancelled'` (row persists). CHECK constraints enforced at the DB layer too (span > 365 and ends < starts rejected by `chk_unavailability_*`). Test rows cleaned up.
|
||||
|
||||
**Decisions:**
|
||||
- **Inclusive on both ends, by design.** A blackout 2026-11-21..2026-11-28 covers 11-28 (the end date), matching the ARCHITECTURE ("inclusive; same day = one day"). `overlapsRange` uses `>=` / `<=` on ISO strings (lexicographic order == chronological for YYYY-MM-DD), so no date parsing is needed.
|
||||
- **`date` columns stored as strings (`mode: "string"`).** The whole recurrence/availability domain works in `YYYY-MM-DD` strings; storing the range as strings avoids Date↔string conversion at the DB boundary. Postgres `date` is mode-agnostic, so the migration is identical to a `mode: "date"` column.
|
||||
- **Range and rrule are mutually exclusive coverage paths.** A record covers a date if it is `active` AND (range contains the date OR rrule matches it). A recurring blackout uses the rrule; a one-time blackout uses the range. `parseRecurrence` throws on malformed input, so `isUnavailable` guards with `validateRecurrence` and never throws.
|
||||
- **Cancel, never delete.** `cancelUnavailability` flips `status='cancelled'`; the row persists so historical assignment conflicts stay explainable (rule 5 in §5.3 warns, doesn't hard-block). `isUnavailable` skips non-`active` records, so a cancelled blackout no longer excludes the volunteer.
|
||||
- **Constraints enforced in two layers.** The pure `validateUnavailabilityRange` rejects bad ranges at the API boundary (400 with a clear message); the DB `chk_unavailability_*` CHECK constraints are the backstop so a bad range can never reach the table.
|
||||
|
||||
**Next: D5 — conflict engine (pure function, hard vs soft conflicts).**
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -32,6 +32,7 @@ yarn-error.log*
|
||||
.pnpm-debug.log*
|
||||
|
||||
# env files (commit .env.example only, never real secrets)
|
||||
.env
|
||||
.env.local
|
||||
.env.*
|
||||
!.env.example
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
CREATE TABLE "unavailability" (
|
||||
"id" text PRIMARY KEY NOT NULL,
|
||||
"user_id" text NOT NULL,
|
||||
"kind" text DEFAULT 'blackout' NOT NULL,
|
||||
"starts_on" date NOT NULL,
|
||||
"ends_on" date NOT NULL,
|
||||
"all_day" boolean DEFAULT true NOT NULL,
|
||||
"reason" text,
|
||||
"rrule" text,
|
||||
"status" text DEFAULT 'active' NOT NULL,
|
||||
"created_at" timestamp with time zone DEFAULT now(),
|
||||
"created_by" text,
|
||||
CONSTRAINT "chk_unavailability_span" CHECK ("unavailability"."ends_on" >= "unavailability"."starts_on"),
|
||||
CONSTRAINT "chk_unavailability_max_span" CHECK ("unavailability"."ends_on" - "unavailability"."starts_on" <= 365)
|
||||
);
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE "unavailability" ADD CONSTRAINT "unavailability_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX "uq_unavailability_range" ON "unavailability" USING btree ("user_id","starts_on","ends_on") WHERE "unavailability"."status" = 'active';--> statement-breakpoint
|
||||
CREATE INDEX "unavailability_user_idx" ON "unavailability" USING btree ("user_id");
|
||||
File diff suppressed because it is too large
Load Diff
@@ -57,6 +57,13 @@
|
||||
"when": 1794976728115,
|
||||
"tag": "0007_funny_zarda",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 8,
|
||||
"version": "7",
|
||||
"when": 1794979809192,
|
||||
"tag": "0008_needy_stryfe",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -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
@@ -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,
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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));
|
||||
}
|
||||
Reference in New Issue
Block a user