phase 2 and 3
This commit is contained in:
@@ -0,0 +1,79 @@
|
||||
import { type NextRequest } from "next/server";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { ok, errorResponse, requireRole, parseJson, ApiError } from "@/lib/api";
|
||||
import { UpdateMachineSchema } from "@/lib/schemas";
|
||||
import { audit } from "@/lib/audit";
|
||||
import { clientIp } from "@/lib/request";
|
||||
|
||||
export async function GET(_req: NextRequest, ctx: { params: Promise<{ id: string }> }) {
|
||||
try {
|
||||
await requireRole("admin");
|
||||
const { id } = await ctx.params;
|
||||
const machine = await prisma.machine.findUnique({ where: { id } });
|
||||
if (!machine) throw new ApiError(404, "not_found", "Machine not found");
|
||||
return ok({ machine });
|
||||
} catch (err) {
|
||||
return errorResponse(err);
|
||||
}
|
||||
}
|
||||
|
||||
export async function PATCH(req: NextRequest, ctx: { params: Promise<{ id: string }> }) {
|
||||
try {
|
||||
const actor = await requireRole("admin");
|
||||
const { id } = await ctx.params;
|
||||
const body = await parseJson(req, UpdateMachineSchema);
|
||||
|
||||
const before = await prisma.machine.findUnique({ where: { id } });
|
||||
if (!before) throw new ApiError(404, "not_found", "Machine not found");
|
||||
|
||||
const updated = await prisma.machine.update({
|
||||
where: { id },
|
||||
data: {
|
||||
...(body.name !== undefined ? { name: body.name } : {}),
|
||||
...(body.kind !== undefined ? { kind: body.kind } : {}),
|
||||
...(body.location !== undefined ? { location: body.location } : {}),
|
||||
...(body.notes !== undefined ? { notes: body.notes } : {}),
|
||||
...(body.active !== undefined ? { active: body.active } : {}),
|
||||
},
|
||||
});
|
||||
await audit({
|
||||
actorId: actor.id,
|
||||
action: "update",
|
||||
entity: "Machine",
|
||||
entityId: id,
|
||||
before,
|
||||
after: updated,
|
||||
ipAddress: clientIp(req),
|
||||
});
|
||||
return ok({ machine: updated });
|
||||
} catch (err) {
|
||||
return errorResponse(err);
|
||||
}
|
||||
}
|
||||
|
||||
export async function DELETE(req: NextRequest, ctx: { params: Promise<{ id: string }> }) {
|
||||
try {
|
||||
const actor = await requireRole("admin");
|
||||
const { id } = await ctx.params;
|
||||
const before = await prisma.machine.findUnique({ where: { id } });
|
||||
if (!before) throw new ApiError(404, "not_found", "Machine not found");
|
||||
|
||||
// soft-delete to preserve references on historical operations
|
||||
const updated = await prisma.machine.update({
|
||||
where: { id },
|
||||
data: { active: false },
|
||||
});
|
||||
await audit({
|
||||
actorId: actor.id,
|
||||
action: "deactivate",
|
||||
entity: "Machine",
|
||||
entityId: id,
|
||||
before,
|
||||
after: updated,
|
||||
ipAddress: clientIp(req),
|
||||
});
|
||||
return ok({ ok: true });
|
||||
} catch (err) {
|
||||
return errorResponse(err);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user