66 lines
2.1 KiB
TypeScript
66 lines
2.1 KiB
TypeScript
import { NextRequest, NextResponse } from "next/server";
|
|
import { prisma } from "@/lib/prisma";
|
|
import { requireAdmin, requireAuth } from "@/lib/session";
|
|
|
|
export async function GET(req: NextRequest) {
|
|
const session = await requireAuth();
|
|
if (!session) return NextResponse.json({ error: "Non autorisé" }, { status: 401 });
|
|
|
|
try {
|
|
if (session.user.role === "ADMIN") {
|
|
const attendances = await prisma.yogaAttendance.findMany({
|
|
orderBy: { date: "desc" },
|
|
include: { profile: { include: { user: { select: { id: true, name: true, email: true } } } } },
|
|
});
|
|
return NextResponse.json(attendances);
|
|
}
|
|
|
|
const profile = await prisma.yogaProfile.findUnique({
|
|
where: { userId: session.user.id },
|
|
include: { attendances: { orderBy: { date: "desc" } } },
|
|
});
|
|
if (!profile) return NextResponse.json({ error: "Profil yoga introuvable" }, { status: 404 });
|
|
return NextResponse.json(profile);
|
|
} catch {
|
|
return NextResponse.json({ error: "Erreur" }, { status: 500 });
|
|
}
|
|
}
|
|
|
|
export async function POST(req: NextRequest) {
|
|
const admin = await requireAdmin();
|
|
if (!admin) return NextResponse.json({ error: "Admin requis" }, { status: 403 });
|
|
|
|
const { userId, pricePaid, notes } = await req.json();
|
|
if (!userId) return NextResponse.json({ error: "userId requis" }, { status: 400 });
|
|
|
|
try {
|
|
const profile = await prisma.yogaProfile.upsert({
|
|
where: { userId },
|
|
update: {},
|
|
create: { userId },
|
|
});
|
|
|
|
if (profile.sessionsRemaining <= 0) {
|
|
return NextResponse.json({ error: "Le membre n'a plus de séances restantes" }, { status: 400 });
|
|
}
|
|
|
|
const attendance = await prisma.yogaAttendance.create({
|
|
data: {
|
|
profileId: profile.id,
|
|
pricePaid: pricePaid ? Number(pricePaid) : null,
|
|
notes: notes || null,
|
|
},
|
|
});
|
|
|
|
await prisma.yogaProfile.update({
|
|
where: { id: profile.id },
|
|
data: { sessionsRemaining: { decrement: 1 } },
|
|
});
|
|
|
|
return NextResponse.json(attendance, { status: 201 });
|
|
} catch (error) {
|
|
console.error(error);
|
|
return NextResponse.json({ error: "Erreur" }, { status: 500 });
|
|
}
|
|
}
|