NeahNew/app/api/missions/route.ts
2025-05-05 13:04:01 +02:00

213 lines
5.5 KiB
TypeScript

import { NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from "@/app/api/auth/options";
import { prisma } from '@/lib/prisma';
// Helper function to check authentication
async function checkAuth(request: Request) {
const session = await getServerSession(authOptions);
if (!session?.user?.id) {
console.error('Unauthorized access attempt:', {
url: request.url,
method: request.method,
headers: Object.fromEntries(request.headers)
});
return { authorized: false, userId: null };
}
return { authorized: true, userId: session.user.id };
}
// GET endpoint to list missions with filters
export async function GET(request: Request) {
try {
const { authorized, userId } = await checkAuth(request);
if (!authorized || !userId) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const { searchParams } = new URL(request.url);
const limit = Number(searchParams.get('limit') || '10');
const offset = Number(searchParams.get('offset') || '0');
const search = searchParams.get('search');
// Build query conditions
const where: any = {};
// Add search filter if provided
if (search) {
where.OR = [
{ name: { contains: search, mode: 'insensitive' } },
{ intention: { contains: search, mode: 'insensitive' } }
];
}
// Get missions with basic info
const missions = await prisma.mission.findMany({
where,
skip: offset,
take: limit,
orderBy: { createdAt: 'desc' },
select: {
id: true,
name: true,
logo: true,
oddScope: true,
niveau: true,
missionType: true,
projection: true,
createdAt: true,
creator: {
select: {
id: true,
email: true
}
},
missionUsers: {
select: {
id: true,
role: true,
user: {
select: {
id: true,
email: true
}
}
}
}
}
});
// Get total count
const totalCount = await prisma.mission.count({ where });
return NextResponse.json({
missions,
pagination: {
total: totalCount,
offset,
limit
}
});
} catch (error) {
console.error('Error listing missions:', error);
return NextResponse.json({
error: 'Internal server error',
details: error instanceof Error ? error.message : String(error)
}, { status: 500 });
}
}
// POST endpoint to create a new mission
export async function POST(request: Request) {
try {
const { authorized, userId } = await checkAuth(request);
if (!authorized || !userId) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
// Parse the request body
const body = await request.json();
const {
name,
logo,
oddScope,
niveau,
intention,
missionType,
donneurDOrdre,
projection,
services,
participation,
profils,
guardians,
volunteers
} = body;
// Validate required fields
if (!name || !niveau || !intention || !missionType || !donneurDOrdre || !projection) {
return NextResponse.json({
error: 'Missing required fields',
required: {
name: true,
niveau: true,
intention: true,
missionType: true,
donneurDOrdre: true,
projection: true
},
received: {
name: !!name,
niveau: !!niveau,
intention: !!intention,
missionType: !!missionType,
donneurDOrdre: !!donneurDOrdre,
projection: !!projection
}
}, { status: 400 });
}
// Create the mission
const mission = await prisma.mission.create({
data: {
name,
logo,
oddScope: oddScope || [],
niveau,
intention,
missionType,
donneurDOrdre,
projection,
services: services || [],
participation,
profils: profils || [],
creatorId: userId
}
});
// Add guardians if provided
if (guardians) {
const guardianRoles = ['gardien-temps', 'gardien-parole', 'gardien-memoire'];
const guardianEntries = Object.entries(guardians)
.filter(([role, userId]) => guardianRoles.includes(role) && userId)
.map(([role, userId]) => ({
role,
userId: userId as string,
missionId: mission.id
}));
if (guardianEntries.length > 0) {
await prisma.missionUser.createMany({
data: guardianEntries
});
}
}
// Add volunteers if provided
if (volunteers && volunteers.length > 0) {
const volunteerEntries = volunteers.map((userId: string) => ({
role: 'volontaire',
userId,
missionId: mission.id
}));
await prisma.missionUser.createMany({
data: volunteerEntries
});
}
return NextResponse.json({
success: true,
mission: {
id: mission.id,
name: mission.name,
createdAt: mission.createdAt
}
});
} catch (error) {
console.error('Error creating mission:', error);
return NextResponse.json({
error: 'Internal server error',
details: error instanceof Error ? error.message : String(error)
}, { status: 500 });
}
}