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
+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;
}