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:
@@ -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");
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user