unit(D8): assign/clear route (schedule.publish guard, rule-1 gate, audit) + active-assignment-in-instance query
This commit is contained in:
@@ -0,0 +1,199 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { and, eq, sql } from "drizzle-orm";
|
||||
import { auth } from "@/auth/config";
|
||||
import { AuthError, requirePermission } from "@/auth/permissions";
|
||||
import type { SystemRole } from "@/auth/roles";
|
||||
import { db } from "@/db";
|
||||
import { assignments, slots } from "@/db/schema";
|
||||
import { writeAudit } from "@/db/audit";
|
||||
import { activeAssignmentInInstance } from "@/db/assignments";
|
||||
import { assignHardConflicts } from "@/domain/assign";
|
||||
import { uuidv7 } from "@/lib/uuid";
|
||||
|
||||
const JSON_HEADERS = { "content-type": "application/json" };
|
||||
|
||||
const bodySchema = z.object({
|
||||
action: z.enum(["assign", "clear"]),
|
||||
slotId: z.string().min(1),
|
||||
userId: z.string().min(1).optional(),
|
||||
});
|
||||
|
||||
/** Walk an error's cause chain to its SQLSTATE (23505 = unique, 23503 = FK). */
|
||||
function sqlStateCode(err: unknown): string | undefined {
|
||||
let node = err as { code?: string; cause?: unknown } | null;
|
||||
while (node) {
|
||||
if (node.code) return node.code;
|
||||
node = (node.cause as { code?: string; cause?: unknown } | null) ?? null;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Assign / clear an assignment (unit D8).
|
||||
*
|
||||
* POST { action: "assign"|"clear", slotId, userId? }
|
||||
*
|
||||
* - assign -> creates a `proposed`/`manual` assignment after the rule-1
|
||||
* duplicate-in-instance gate; writes an `assignment.created`
|
||||
* audit row.
|
||||
* - clear -> deletes the active assignment on the slot; writes an
|
||||
* `assignment.cleared` audit row.
|
||||
*
|
||||
* Guarded by `schedule.publish` (coordinator + admin). Hard conflicts reject
|
||||
* 409; a DB unique violation on the slot rejects 409 (rule 2).
|
||||
*/
|
||||
export const POST = async (req: NextRequest) => {
|
||||
let action: string | undefined;
|
||||
let slotId: string | undefined;
|
||||
let userId: string | undefined;
|
||||
try {
|
||||
const body = JSON.parse(await req.text()) as {
|
||||
action?: string;
|
||||
slotId?: string;
|
||||
userId?: string;
|
||||
};
|
||||
action = body.action;
|
||||
slotId = body.slotId;
|
||||
userId = body.userId;
|
||||
} catch {
|
||||
// fall through to validation
|
||||
}
|
||||
|
||||
const parsed = bodySchema.safeParse({ action, slotId, userId });
|
||||
if (!parsed.success) {
|
||||
return new Response(JSON.stringify({ error: "an action and slotId are required" }), {
|
||||
status: 400,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
const session = await auth();
|
||||
const user = (session?.user as { id: string; systemRole: SystemRole } | null | undefined);
|
||||
if (!user) {
|
||||
return new Response(JSON.stringify({ error: "Authentication required", code: "UNAUTHORIZED" }), {
|
||||
status: 401,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
requirePermission(user, "schedule.publish");
|
||||
const actorId = user.id;
|
||||
|
||||
if (parsed.data.action === "clear") {
|
||||
const active = await db
|
||||
.select({ id: assignments.id })
|
||||
.from(assignments)
|
||||
.where(
|
||||
and(
|
||||
eq(assignments.slotId, parsed.data.slotId),
|
||||
sql`${assignments.status} IN ('proposed','confirmed','completed')`,
|
||||
),
|
||||
)
|
||||
.limit(1);
|
||||
|
||||
if (active.length === 0) {
|
||||
return new Response(JSON.stringify({ error: "no active assignment on this slot" }), {
|
||||
status: 404,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
|
||||
await db.delete(assignments).where(eq(assignments.id, active[0].id));
|
||||
await writeAudit(db, {
|
||||
actorId,
|
||||
action: "assignment.cleared",
|
||||
entityType: "assignment",
|
||||
entityId: active[0].id,
|
||||
after: { slotId: parsed.data.slotId },
|
||||
});
|
||||
return new Response(JSON.stringify({ ok: true }), {
|
||||
status: 200,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
|
||||
// assign
|
||||
if (!parsed.data.userId) {
|
||||
return new Response(JSON.stringify({ error: "a userId is required to assign" }), {
|
||||
status: 400,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
|
||||
const slotRows = await db
|
||||
.select({ id: slots.id, serviceInstanceId: slots.serviceInstanceId })
|
||||
.from(slots)
|
||||
.where(eq(slots.id, parsed.data.slotId))
|
||||
.limit(1);
|
||||
if (slotRows.length === 0) {
|
||||
return new Response(JSON.stringify({ error: "unknown slot" }), {
|
||||
status: 404,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
const instanceId = slotRows[0].serviceInstanceId;
|
||||
if (!instanceId) {
|
||||
return new Response(JSON.stringify({ error: "slot is not attached to a service instance" }), {
|
||||
status: 400,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
|
||||
const existing = await activeAssignmentInInstance(db, {
|
||||
userId: parsed.data.userId,
|
||||
instanceId,
|
||||
});
|
||||
const conflicts = assignHardConflicts({ alreadyAssignedInInstance: existing != null });
|
||||
if (conflicts.length > 0) {
|
||||
return new Response(JSON.stringify({ error: conflicts[0].message, code: conflicts[0].code }), {
|
||||
status: 409,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
|
||||
const result = await db
|
||||
.insert(assignments)
|
||||
.values({
|
||||
id: uuidv7(),
|
||||
slotId: parsed.data.slotId,
|
||||
userId: parsed.data.userId,
|
||||
status: "proposed",
|
||||
source: "manual",
|
||||
assignedBy: actorId,
|
||||
assignedAt: new Date(),
|
||||
})
|
||||
.returning({ id: assignments.id, status: assignments.status });
|
||||
|
||||
await writeAudit(db, {
|
||||
actorId,
|
||||
action: "assignment.created",
|
||||
entityType: "assignment",
|
||||
entityId: result[0].id,
|
||||
before: { slotId: parsed.data.slotId },
|
||||
after: { slotId: parsed.data.slotId, userId: parsed.data.userId, status: "proposed" },
|
||||
});
|
||||
|
||||
return new Response(JSON.stringify({ ok: true, id: result[0].id, status: result[0].status }), {
|
||||
status: 201,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
} catch (e) {
|
||||
if (e instanceof AuthError) {
|
||||
return new Response(JSON.stringify({ error: e.message, code: e.code }), {
|
||||
status: e.status,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
if (sqlStateCode(e) === "23505") {
|
||||
return new Response(JSON.stringify({ error: "slot already has an active assignment", code: "slot_taken" }), {
|
||||
status: 409,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
return new Response(JSON.stringify({ error: "failed to assign" }), {
|
||||
status: 500,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,42 @@
|
||||
import { and, eq, sql } from "drizzle-orm";
|
||||
import { assignments } from "@/db/schema";
|
||||
|
||||
/**
|
||||
* Assignment queries — unit D8.
|
||||
*
|
||||
* `activeAssignmentInInstance` returns a volunteer's single active assignment
|
||||
* within one service instance, or null. It keys on the instance id rather than
|
||||
* a date range: rule 1 (BUILD-SPEC §7) is "one active assignment per service
|
||||
* instance", and a volunteer may serve two different instances on the same day
|
||||
* (e.g. both Sunday services). A date range would wrongly block that.
|
||||
*/
|
||||
|
||||
export interface ActiveAssignment {
|
||||
id: string;
|
||||
slotId: string;
|
||||
userId: string;
|
||||
status: string;
|
||||
}
|
||||
|
||||
export async function activeAssignmentInInstance(
|
||||
db: typeof import("@/db").db,
|
||||
input: { userId: string; instanceId: string },
|
||||
): Promise<ActiveAssignment | null> {
|
||||
const rows = await db
|
||||
.select({
|
||||
id: assignments.id,
|
||||
slotId: assignments.slotId,
|
||||
userId: assignments.userId,
|
||||
status: assignments.status,
|
||||
})
|
||||
.from(assignments)
|
||||
.where(
|
||||
and(
|
||||
eq(assignments.userId, input.userId),
|
||||
sql`${assignments.slotId} IN (SELECT id FROM slots WHERE service_instance_id = ${input.instanceId})`,
|
||||
sql`${assignments.status} IN ('proposed','confirmed','completed')`,
|
||||
),
|
||||
)
|
||||
.limit(1);
|
||||
return rows[0] ?? null;
|
||||
}
|
||||
Reference in New Issue
Block a user