unit(D8): assign/clear route (schedule.publish guard, rule-1 gate, audit) + active-assignment-in-instance query

This commit is contained in:
Tiel Coder
2026-11-18 18:35:53 +00:00
parent e47ef839a7
commit 71b993e663
2 changed files with 241 additions and 0 deletions
+199
View File
@@ -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,
});
}
};