import type { NextRequest } from "next/server"; import { revalidatePath } from "next/cache"; import { prisma } from "@/lib/prisma"; import { apiCreated, apiOk, readJsonBody } from "@/lib/api-response"; import { apiRoute, parseQuery } from "@/lib/api-route"; import { apiListQuerySchema, apiQuoteCreateSchema } from "@/lib/api-validations"; import { createQuoteFromApi } from "@/lib/api-quotes"; /** * GET /api/v1/quotes — list quotes, newest first. * * Query: `limit` (1–100, default 25), `offset`, `status`, `clientId`, * `search` (matches project title or code). */ export const GET = apiRoute("read", async (req: NextRequest) => { const { limit, offset, status, clientId, search } = parseQuery(apiListQuerySchema, req); const where = { ...(status ? { status } : {}), ...(clientId ? { clientId } : {}), ...(search ? { OR: [ { projectTitle: { contains: search, mode: "insensitive" as const } }, { projectCode: { contains: search, mode: "insensitive" as const } }, ], } : {}), }; const [quotes, total] = await Promise.all([ prisma.job.findMany({ where, orderBy: { createdAt: "desc" }, take: limit, skip: offset, include: { client: { select: { id: true, companyName: true, contactPerson: true } }, _count: { select: { shots: true, assets: true, supervisions: true, previses: true } }, }, }), prisma.job.count({ where }), ]); return apiOk(quotes, { total, limit, offset, returned: quotes.length }); }); /** * POST /api/v1/quotes — create a quote, optionally with its whole * shot/asset/task tree in the same request. Runs in one transaction. */ export const POST = apiRoute("write", async (req: NextRequest) => { const input = apiQuoteCreateSchema.parse(await readJsonBody(req)); const quote = await createQuoteFromApi(input); revalidatePath("/jobs"); return apiCreated(quote); });