NeahNew/app/api/missions/route.ts
2025-05-23 10:33:31 +02:00

367 lines
11 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[];
logo?: string | null;
leantimeProjectId?: string;
documentationCollectionId?: string;
rocketchatChannelId?: string;
gitRepoUrl?: string;
penpotProjectId?: string;
}
interface MissionUserInput {
role: string;
userId: string;
missionId: string;
}
// Helper function to check authentication
async function checkAuth(request: Request) {
const apiKey = request.headers.get('x-api-key');
if (apiKey === process.env.N8N_API_KEY) {
return { authorized: true, userId: 'system' };
}
const session = await getServerSession(authOptions);
if (!session?.user?.id) {
return { authorized: false, userId: null };
}
return { authorized: true, 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
}
}
}
}
}
});
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 });
}
const requestId = request.headers.get('x-request-id');
const body = await request.json() as MissionCreateInput;
// Validate required fields
const requiredFields = ['name', 'niveau', 'intention', 'missionType', 'donneurDOrdre', 'projection'];
const missingFields = requiredFields.filter(field => !body[field as keyof MissionCreateInput]);
if (missingFields.length > 0) {
return NextResponse.json({
error: 'Missing required fields',
missingFields
}, { status: 400 });
}
// Verify that the creator exists
const creator = await prisma.user.findUnique({
where: { id: userId }
});
if (!creator) {
return NextResponse.json({
error: 'Invalid creator ID',
details: 'The specified creator does not exist',
code: 'INVALID_CREATOR'
}, { status: 400 });
}
// Check if mission with same name exists
const existingMission = await prisma.mission.findFirst({
where: { name: body.name }
});
if (existingMission) {
// Update existing mission with new integration IDs
const updatedMission = await prisma.mission.update({
where: { id: existingMission.id },
data: {
leantimeProjectId: body.leantimeProjectId || null,
outlineCollectionId: body.documentationCollectionId || null,
rocketChatChannelId: body.rocketchatChannelId || null,
giteaRepositoryUrl: body.gitRepoUrl || null,
penpotProjectId: body.penpotProjectId || null
} as Prisma.MissionUpdateInput
});
return NextResponse.json({
message: 'Mission updated successfully',
mission: updatedMission,
isUpdate: true
});
}
// Check for mission creation in progress
const missionInProgress = await prisma.mission.findFirst({
where: {
name: body.name,
createdAt: {
gte: new Date(Date.now() - 5 * 60 * 1000) // Within last 5 minutes
}
}
});
if (missionInProgress) {
return NextResponse.json({
error: 'Mission creation already in progress',
details: 'Please wait a few minutes and try again',
code: 'MISSION_CREATION_IN_PROGRESS'
}, { status: 409 });
}
// Check if this is a request from n8n
const isN8nRequest = request.headers.get('x-api-key') === process.env.N8N_API_KEY;
if (!isN8nRequest) {
// Trigger n8n workflow
const n8nService = new N8nService();
// Prepare the data for n8n
const n8nData = {
name: body.name,
oddScope: Array.isArray(body.oddScope) ? body.oddScope : [body.oddScope],
niveau: body.niveau || 'default',
intention: body.intention?.trim() || '',
missionType: body.missionType || 'default',
donneurDOrdre: body.donneurDOrdre || 'default',
projection: body.projection || 'default',
services: Array.isArray(body.services) ? body.services : [],
participation: body.participation || 'default',
profils: Array.isArray(body.profils) ? body.profils : [],
guardians: body.guardians || {},
volunteers: Array.isArray(body.volunteers) ? body.volunteers : [],
creatorId: userId,
config: {
N8N_API_KEY: process.env.N8N_API_KEY,
MISSION_API_URL: process.env.NEXT_PUBLIC_API_URL || 'https://api.slm-lab.net/api'
}
};
try {
console.log('Sending data to n8n workflow:', {
...n8nData,
config: { ...n8nData.config, N8N_API_KEY: '[REDACTED]' } // Don't log sensitive data
});
const workflowResult = await n8nService.triggerMissionCreation(n8nData);
if (!workflowResult.success) {
console.error('n8n workflow failed:', workflowResult.error);
return NextResponse.json({
error: 'Failed to create mission resources',
details: workflowResult.error || 'The mission creation process failed',
code: 'WORKFLOW_ERROR'
}, { status: 500 });
}
return NextResponse.json(workflowResult);
} catch (error) {
console.error('Error triggering n8n workflow:', error);
// Check if it's an n8n workflow error
if (error instanceof Error && error.message.includes('HTTP error! status: 500')) {
return NextResponse.json(
{
error: 'Mission creation workflow failed',
details: 'The mission creation process encountered an error. Please try again later.',
code: 'WORKFLOW_ERROR',
originalError: error.message
},
{ status: 500 }
);
}
// Handle other types of errors
return NextResponse.json(
{
error: 'Failed to create mission resources',
details: error instanceof Error ? error.message : 'The mission creation process failed. Please try again later.',
code: 'WORKFLOW_ERROR'
},
{ status: 500 }
);
}
}
// Create mission directly (n8n request)
try {
const mission = await prisma.mission.create({
data: {
name: body.name,
oddScope: body.oddScope || ['default'],
niveau: body.niveau,
intention: body.intention,
missionType: body.missionType,
donneurDOrdre: body.donneurDOrdre,
projection: body.projection,
services: Array.isArray(body.services) ? body.services.filter(Boolean) : [],
profils: Array.isArray(body.profils) ? body.profils.filter(Boolean) : [],
participation: body.participation || 'default',
creatorId: userId,
logo: body.logo || null,
leantimeProjectId: body.leantimeProjectId || null,
outlineCollectionId: body.documentationCollectionId || null,
rocketChatChannelId: body.rocketchatChannelId || null,
giteaRepositoryUrl: body.gitRepoUrl || null,
penpotProjectId: body.penpotProjectId || null
} as Prisma.MissionUncheckedCreateInput
});
// Add guardians and volunteers
if (body.guardians || body.volunteers) {
const missionUsers: MissionUserInput[] = [];
// Add guardians
if (body.guardians) {
Object.entries(body.guardians).forEach(([role, userId]) => {
if (userId) {
missionUsers.push({
role,
userId: userId as string,
missionId: mission.id
});
}
});
}
// Add volunteers
if (body.volunteers && Array.isArray(body.volunteers)) {
body.volunteers.forEach(userId => {
if (userId) {
missionUsers.push({
role: 'volontaire',
userId,
missionId: mission.id
});
}
});
}
if (missionUsers.length > 0) {
await prisma.missionUser.createMany({
data: missionUsers
});
}
}
return NextResponse.json({
message: 'Mission created successfully',
mission
});
} catch (error) {
console.error('Error creating mission:', error);
if (error instanceof Prisma.PrismaClientKnownRequestError) {
if (error.code === 'P2003') {
return NextResponse.json({
error: 'Invalid reference',
details: 'One or more referenced users do not exist',
code: 'INVALID_REFERENCE'
}, { status: 400 });
}
}
return NextResponse.json(
{
error: 'Failed to create mission',
details: error instanceof Error ? error.message : String(error)
},
{ status: 500 }
);
}
} catch (error) {
console.error('Error creating mission:', error);
return NextResponse.json(
{
error: 'Failed to create mission',
details: error instanceof Error ? error.message : String(error)
},
{ status: 500 }
);
}
}