import { type NextRequest } from "next/server"; import { prisma } from "@/lib/prisma"; import { ok, errorResponse, requireRole, parseJson, ApiError } from "@/lib/api"; import { CreatePOSchema } from "@/lib/schemas"; import { audit } from "@/lib/audit"; import { clientIp } from "@/lib/request"; /** * List purchase orders on a project with summary totals so the UI can show * "draft / sent / received" status and a line/dollar summary without a * second round-trip. */ export async function GET(_req: NextRequest, ctx: { params: Promise<{ id: string }> }) { try { await requireRole("admin"); const { id } = await ctx.params; const pos = await prisma.purchaseOrder.findMany({ where: { projectId: id }, orderBy: [{ createdAt: "desc" }], include: { lines: { select: { qty: true, receivedQty: true, unitCost: true, fastener: { select: { partNumber: true, description: true, unitCost: true } }, }, }, }, }); const rows = pos.map((po) => { const totalQty = po.lines.reduce((a, l) => a + l.qty, 0); const totalReceived = po.lines.reduce((a, l) => a + l.receivedQty, 0); const totalCost = po.lines.reduce((acc, l) => { const cost = l.unitCost ?? l.fastener.unitCost ?? 0; return acc + cost * l.qty; }, 0); return { id: po.id, vendor: po.vendor, status: po.status, createdAt: po.createdAt, sentAt: po.sentAt, receivedAt: po.receivedAt, notes: po.notes, lineCount: po.lines.length, totalQty, totalReceived, totalCost, }; }); return ok({ purchaseOrders: rows }); } 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, CreatePOSchema); const project = await prisma.project.findUnique({ where: { id }, select: { id: true } }); if (!project) throw new ApiError(404, "not_found", "Project not found"); // Validate every fastener on every line belongs to this project. const fastenerIds = [...new Set(body.lines.map((l) => l.fastenerId))]; const fasteners = await prisma.fastener.findMany({ where: { id: { in: fastenerIds }, projectId: id }, select: { id: true }, }); if (fasteners.length !== fastenerIds.length) { throw new ApiError( 400, "invalid_fasteners", "One or more fasteners don't belong to this project", ); } const created = await prisma.purchaseOrder.create({ data: { projectId: id, vendor: body.vendor, notes: body.notes ?? null, status: "draft", lines: { create: body.lines.map((l) => ({ fastenerId: l.fastenerId, qty: l.qty, unitCost: l.unitCost ?? null, })), }, }, include: { lines: true }, }); await audit({ actorId: actor.id, action: "create", entity: "PurchaseOrder", entityId: created.id, after: created, ipAddress: clientIp(req), }); return ok({ purchaseOrder: created }, { status: 201 }); } catch (err) { return errorResponse(err); } }