import { type NextRequest } from "next/server"; import { prisma } from "@/lib/prisma"; import { ok, errorResponse, requireRole, parseJson, ApiError } from "@/lib/api"; import { UpdatePOSchema } 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 po = await prisma.purchaseOrder.findUnique({ where: { id }, include: { project: { select: { id: true, code: true, name: true } }, lines: { include: { fastener: { select: { id: true, partNumber: true, description: true, unitCost: true, supplier: true, }, }, }, }, }, }); if (!po) throw new ApiError(404, "not_found", "Purchase order not found"); return ok({ purchaseOrder: po }); } catch (err) { return errorResponse(err); } } /** * Update vendor/notes any time. Lines can only be rewritten while the PO is * still in draft — once sent we freeze the line items so the vendor record * stays truthful. Rewriting lines is a full replace (delete + insert) so * the caller passes the complete desired list. */ 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, UpdatePOSchema); const before = await prisma.purchaseOrder.findUnique({ where: { id }, include: { lines: true }, }); if (!before) throw new ApiError(404, "not_found", "Purchase order not found"); if (body.lines && before.status !== "draft") { throw new ApiError(409, "po_locked", "Lines can only be edited on a draft PO"); } const after = await prisma.$transaction(async (tx) => { if (body.lines) { // Validate fastener ownership in the project before mutating anything. const fastenerIds = [...new Set(body.lines.map((l) => l.fastenerId))]; const owned = await tx.fastener.findMany({ where: { id: { in: fastenerIds }, projectId: before.projectId }, select: { id: true }, }); if (owned.length !== fastenerIds.length) { throw new ApiError( 400, "invalid_fasteners", "One or more fasteners don't belong to this project", ); } await tx.pOLine.deleteMany({ where: { poId: id } }); } const updated = await tx.purchaseOrder.update({ where: { id }, data: { vendor: body.vendor ?? undefined, notes: body.notes === undefined ? undefined : (body.notes ?? null), ...(body.lines ? { lines: { create: body.lines.map((l) => ({ fastenerId: l.fastenerId, qty: l.qty, unitCost: l.unitCost ?? null, })), }, } : {}), }, include: { lines: true }, }); return updated; }); await audit({ actorId: actor.id, action: "update", entity: "PurchaseOrder", entityId: id, before, after, ipAddress: clientIp(req), }); return ok({ purchaseOrder: after }); } 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.purchaseOrder.findUnique({ where: { id } }); if (!before) throw new ApiError(404, "not_found", "Purchase order not found"); // Only allow hard-delete of drafts. Anything further along has to be // cancelled via the status endpoint, which preserves the audit trail. if (before.status !== "draft") { throw new ApiError(409, "po_locked", "Only draft POs can be deleted; cancel instead"); } await prisma.purchaseOrder.delete({ where: { id } }); await audit({ actorId: actor.id, action: "delete", entity: "PurchaseOrder", entityId: id, before, ipAddress: clientIp(req), }); return ok({ ok: true }); } catch (err) { return errorResponse(err); } }