63 lines
1.9 KiB
TypeScript
63 lines
1.9 KiB
TypeScript
import { NextResponse } from "next/server";
|
|
import { auth } from "@/auth";
|
|
import { db } from "@/lib/db";
|
|
|
|
export async function GET(req: Request) {
|
|
const session = await auth();
|
|
if (!session?.user) {
|
|
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
|
}
|
|
|
|
const { searchParams } = new URL(req.url);
|
|
const q = searchParams.get("q") ?? "";
|
|
const status = searchParams.get("status");
|
|
|
|
const [projects, shotGroups] = await Promise.all([
|
|
db.project.findMany({
|
|
where: {
|
|
AND: [
|
|
q
|
|
? {
|
|
OR: [
|
|
{ name: { contains: q, mode: "insensitive" } },
|
|
{ code: { contains: q, mode: "insensitive" } },
|
|
],
|
|
}
|
|
: {},
|
|
status ? { status: status as any } : {},
|
|
],
|
|
},
|
|
orderBy: { createdAt: "desc" },
|
|
include: {
|
|
client: { select: { id: true, company: true } },
|
|
producer: { select: { id: true, name: true, image: true } },
|
|
},
|
|
}),
|
|
// Single query to get shot counts grouped by project + status
|
|
db.shot.groupBy({
|
|
by: ["projectId", "status"],
|
|
_count: { id: true },
|
|
}),
|
|
]);
|
|
|
|
// Build shotStats map keyed by projectId
|
|
const statsMap = new Map<string, { total: number; approved: number; inProgress: number }>();
|
|
for (const row of shotGroups) {
|
|
const existing = statsMap.get(row.projectId) ?? { total: 0, approved: 0, inProgress: 0 };
|
|
existing.total += row._count.id;
|
|
if (row.status === "COMPLETE") {
|
|
existing.approved += row._count.id;
|
|
} else if (row.status !== "WAITING") {
|
|
existing.inProgress += row._count.id;
|
|
}
|
|
statsMap.set(row.projectId, existing);
|
|
}
|
|
|
|
const projectsWithStats = projects.map((p) => ({
|
|
...p,
|
|
shotStats: statsMap.get(p.id) ?? { total: 0, approved: 0, inProgress: 0 },
|
|
}));
|
|
|
|
return NextResponse.json({ projects: projectsWithStats });
|
|
}
|