+46
-22
@@ -12,27 +12,51 @@ export async function GET(req: Request) {
|
||||
const q = searchParams.get("q") ?? "";
|
||||
const status = searchParams.get("status");
|
||||
|
||||
const projects = await 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 } },
|
||||
_count: { select: { shots: true } },
|
||||
},
|
||||
});
|
||||
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 },
|
||||
}),
|
||||
]);
|
||||
|
||||
return NextResponse.json({ projects });
|
||||
// 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 });
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user