55 lines
1.6 KiB
TypeScript
55 lines
1.6 KiB
TypeScript
import { type NextRequest } from "next/server";
|
|
import { prisma } from "@/lib/prisma";
|
|
import { ok, errorResponse, requireRole, parseJson, ApiError } from "@/lib/api";
|
|
import { CreatePartSchema } 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 parts = await prisma.part.findMany({
|
|
where: { assemblyId: id },
|
|
orderBy: { code: "asc" },
|
|
include: { _count: { select: { operations: true } } },
|
|
});
|
|
return ok({ parts });
|
|
} catch (err) {
|
|
return errorResponse(err);
|
|
}
|
|
}
|
|
|
|
export async function POST(req: NextRequest, ctx: { params: Promise<{ id: string }> }) {
|
|
try {
|
|
const actor = await requireRole("admin");
|
|
const { id } = await ctx.params;
|
|
const body = await parseJson(req, CreatePartSchema);
|
|
|
|
const assembly = await prisma.assembly.findUnique({ where: { id } });
|
|
if (!assembly) throw new ApiError(404, "not_found", "Assembly not found");
|
|
|
|
const created = await prisma.part.create({
|
|
data: {
|
|
assemblyId: id,
|
|
code: body.code,
|
|
name: body.name,
|
|
material: body.material ?? null,
|
|
qty: body.qty,
|
|
notes: body.notes ?? null,
|
|
},
|
|
});
|
|
await audit({
|
|
actorId: actor.id,
|
|
action: "create",
|
|
entity: "Part",
|
|
entityId: created.id,
|
|
after: created,
|
|
ipAddress: clientIp(req),
|
|
});
|
|
return ok({ part: created }, { status: 201 });
|
|
} catch (err) {
|
|
return errorResponse(err);
|
|
}
|
|
}
|