NeahNew/app/api/missions/route.ts
2025-05-24 12:29:04 +02:00

298 lines
8.4 KiB
TypeScript

import { NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from "@/app/api/auth/options";
import { prisma } from '@/lib/prisma';
import { N8nService } from '@/lib/services/n8n-service';
import { Prisma } from '@prisma/client';
// Types
interface MissionCreateInput {
name: string;
oddScope: string[];
niveau?: string;
intention?: string;
missionType?: string;
donneurDOrdre?: string;
projection?: string;
services?: string[];
participation?: string;
profils?: string[];
guardians?: Record<string, string>;
volunteers?: string[];
creatorId?: string;
logo?: {
data: string;
name?: string;
type?: string;
} | null;
attachments?: Array<{
data: string;
name?: string;
type?: string;
}>;
leantimeProjectId?: string | null;
outlineCollectionId?: string | null;
rocketChatChannelId?: string | null;
giteaRepositoryUrl?: string | null;
penpotProjectId?: string | null;
}
interface MissionUserInput {
role: string;
userId: string;
missionId: string;
}
interface MissionResponse {
id: string;
name: string;
oddScope: string[];
niveau: string;
intention: string;
missionType: string;
donneurDOrdre: string;
projection: string;
services: string[];
profils: string[];
participation: string;
creatorId: string;
logo: string | null;
leantimeProjectId: string | null;
outlineCollectionId: string | null;
rocketChatChannelId: string | null;
giteaRepositoryUrl: string | null;
penpotProjectId: string | null;
createdAt: Date;
updatedAt: Date;
attachments?: Array<{
id: string;
filename: string;
filePath: string;
fileType: string;
fileSize: number;
createdAt: Date;
}>;
}
// Helper function to check authentication
async function checkAuth(request: Request) {
const session = await getServerSession(authOptions);
return {
authorized: !!session?.user,
userId: session?.user?.id
};
}
// GET endpoint to list missions
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');
const name = searchParams.get('name');
const where: Prisma.MissionWhereInput = {};
if (search) {
where.OR = [
{ name: { contains: search, mode: 'insensitive' } },
{ intention: { contains: search, mode: 'insensitive' } }
];
}
if (name) {
where.name = name;
}
const missions = await prisma.mission.findMany({
where,
skip: offset,
take: limit,
orderBy: { createdAt: 'desc' },
include: {
creator: {
select: {
id: true,
email: true
}
},
missionUsers: {
include: {
user: {
select: {
id: true,
email: true
}
}
}
},
attachments: {
select: {
id: true,
filename: true,
filePath: true,
fileType: true,
fileSize: true,
createdAt: true
},
orderBy: { createdAt: 'desc' }
}
}
});
const totalCount = await prisma.mission.count({ where });
// Transform missions to include public URLs
const missionsWithUrls = missions.map(mission => ({
...mission,
logoUrl: mission.logo ? `/api/missions/image/${mission.logo.replace('missions/', '')}` : null,
logo: mission.logo,
attachments: mission.attachments?.map(attachment => ({
...attachment,
publicUrl: `/api/missions/image/${attachment.filePath.replace('missions/', '')}`
})) || []
}));
return NextResponse.json({
missions: missionsWithUrls,
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 });
}
const body = await request.json();
// Simple validation
if (!body.name || !body.oddScope) {
return NextResponse.json({
error: 'Missing required fields',
missingFields: ['name', 'oddScope'].filter(field => !body[field])
}, { status: 400 });
}
// Check if this is a request from n8n
const isN8nRequest = request.headers.get('x-api-key') === process.env.N8N_API_KEY;
if (!isN8nRequest) {
try {
const n8nService = new N8nService();
// Prepare data for n8n
const n8nData = {
...body,
creatorId: userId,
config: {
N8N_API_KEY: process.env.N8N_API_KEY,
MISSION_API_URL: process.env.NEXT_PUBLIC_API_URL
}
};
// Trigger n8n workflow first
const workflowResult = await n8nService.triggerMissionCreation(n8nData);
if (!workflowResult.success) {
return NextResponse.json({
error: 'Failed to create mission resources',
details: workflowResult.error
}, { status: 500 });
}
// Only create mission in database after n8n succeeds
try {
const missionData = {
name: body.name,
oddScope: body.oddScope,
niveau: body.niveau,
intention: body.intention,
missionType: body.missionType,
donneurDOrdre: body.donneurDOrdre,
projection: body.projection,
services: body.services,
profils: body.profils,
participation: body.participation,
creatorId: userId,
logo: body.logo
};
const mission = await prisma.mission.create({
data: missionData
});
return NextResponse.json({
success: true,
mission,
message: 'Mission created successfully with all integrations'
});
} catch (dbError) {
console.error('Database error creating mission:', dbError);
return NextResponse.json({
error: 'Failed to create mission in database',
details: dbError instanceof Error ? dbError.message : String(dbError)
}, { status: 500 });
}
} catch (n8nError) {
console.error('Error with n8n service:', n8nError);
return NextResponse.json({
error: 'Failed to create mission resources',
details: n8nError instanceof Error ? n8nError.message : String(n8nError)
}, { status: 500 });
}
} else {
// Handle n8n callback - update mission with integration IDs
try {
const mission = await prisma.mission.update({
where: { id: body.missionId },
data: {
leantimeProjectId: body.leantimeProjectId ? String(body.leantimeProjectId) : null,
outlineCollectionId: body.outlineCollectionId || null,
rocketChatChannelId: body.rocketChatChannelId || null,
giteaRepositoryUrl: body.giteaRepositoryUrl || null,
penpotProjectId: body.penpotProjectId || null
} as Prisma.MissionUpdateInput
});
return NextResponse.json({
success: true,
mission,
message: 'Mission updated with integration IDs'
});
} catch (dbError) {
console.error('Database error updating mission:', dbError);
return NextResponse.json({
error: 'Failed to update mission with integration IDs',
details: dbError instanceof Error ? dbError.message : String(dbError)
}, { status: 500 });
}
}
} catch (error) {
console.error('Error in mission creation:', error);
return NextResponse.json({
error: 'Failed to create mission',
details: error instanceof Error ? error.message : String(error)
}, { status: 500 });
}
}