import { NextResponse } from 'next/server'; import { prisma } from '@/lib/prisma'; import { logger } from '@/lib/logger'; /** * POST /api/missions/mission-created * * Endpoint appelé par N8N après la création des intégrations externes. * Reçoit les IDs des intégrations créées et met à jour la mission en base. * * Headers attendus: * - Authorization: Bearer {keycloak_token} (optionnel, vérifié via x-api-key) * - x-api-key: {N8N_API_KEY} * * Body attendu (format N8N): * { * name: string, * creatorId: string, * gitRepoUrl?: string, * leantimeProjectId?: string, * documentationCollectionId?: string, * rocketchatChannelId?: string, * // ... autres champs optionnels * } */ export async function POST(request: Request) { try { logger.debug('Mission Created Webhook Received'); // Vérifier l'API key const apiKey = request.headers.get('x-api-key'); const expectedApiKey = process.env.N8N_API_KEY; if (!expectedApiKey) { logger.error('N8N_API_KEY not configured in environment'); return NextResponse.json( { error: 'Server configuration error' }, { status: 500 } ); } if (apiKey !== expectedApiKey) { logger.error('Invalid API key', { received: apiKey ? 'present' : 'missing', expected: expectedApiKey ? 'configured' : 'missing' }); return NextResponse.json( { error: 'Unauthorized' }, { status: 401 } ); } const body = await request.json(); logger.debug('Received mission-created data', { hasMissionId: !!body.missionId, hasName: !!body.name, hasCreatorId: !!body.creatorId }); // Validation des champs requis // Prefer missionId if provided, otherwise use name + creatorId let mission; if (body.missionId) { // ✅ Use missionId if provided (more reliable) logger.debug('Looking up mission by ID', { missionId: body.missionId }); mission = await prisma.mission.findUnique({ where: { id: body.missionId } }); } else if (body.name && body.creatorId) { // Fallback to name + creatorId (for backward compatibility) logger.debug('Looking up mission by name + creatorId', { name: body.name, creatorId: body.creatorId }); mission = await prisma.mission.findFirst({ where: { name: body.name, creatorId: body.creatorId }, orderBy: { createdAt: 'desc' // Prendre la plus récente } }); } else { logger.error('Missing required fields', { hasMissionId: !!body.missionId, hasName: !!body.name, hasCreatorId: !!body.creatorId }); return NextResponse.json( { error: 'Missing required fields: missionId OR (name and creatorId)' }, { status: 400 } ); } if (!mission) { logger.error('Mission not found', { missionId: body.missionId, name: body.name, creatorId: body.creatorId }); return NextResponse.json( { error: 'Mission not found' }, { status: 404 } ); } logger.debug('Found mission', { id: mission.id, name: mission.name, hasIntegrations: { gitea: !!mission.giteaRepositoryUrl, leantime: !!mission.leantimeProjectId, outline: !!mission.outlineCollectionId, rocketChat: !!mission.rocketChatChannelId } }); // Préparer les données de mise à jour const updateData: { giteaRepositoryUrl?: string | null; leantimeProjectId?: string | null; outlineCollectionId?: string | null; rocketChatChannelId?: string | null; } = {}; // Mapper les champs N8N vers notre schéma Prisma if (body.gitRepoUrl !== undefined) { updateData.giteaRepositoryUrl = body.gitRepoUrl || null; logger.debug('Updating giteaRepositoryUrl', { hasUrl: !!body.gitRepoUrl }); } if (body.leantimeProjectId !== undefined) { // N8N peut retourner un number, on le convertit en string updateData.leantimeProjectId = body.leantimeProjectId ? String(body.leantimeProjectId) : null; logger.debug('Updating leantimeProjectId', { hasId: !!updateData.leantimeProjectId }); } if (body.documentationCollectionId !== undefined) { updateData.outlineCollectionId = body.documentationCollectionId || null; logger.debug('Updating outlineCollectionId', { hasId: !!updateData.outlineCollectionId }); } if (body.rocketchatChannelId !== undefined) { updateData.rocketChatChannelId = body.rocketchatChannelId || null; logger.debug('Updating rocketChatChannelId', { hasId: !!updateData.rocketChatChannelId }); } // Vérifier qu'il y a au moins un champ à mettre à jour if (Object.keys(updateData).length === 0) { logger.warn('No integration IDs to update'); return NextResponse.json({ message: 'Mission found but no integration IDs provided', mission: { id: mission.id, name: mission.name } }); } // Mettre à jour la mission const updatedMission = await prisma.mission.update({ where: { id: mission.id }, data: updateData }); logger.debug('Mission updated successfully', { id: updatedMission.id, name: updatedMission.name, updatedFields: Object.keys(updateData) }); return NextResponse.json({ success: true, message: 'Mission updated successfully', mission: { id: updatedMission.id, name: updatedMission.name, giteaRepositoryUrl: updatedMission.giteaRepositoryUrl, leantimeProjectId: updatedMission.leantimeProjectId, outlineCollectionId: updatedMission.outlineCollectionId, rocketChatChannelId: updatedMission.rocketChatChannelId } }); } catch (error) { logger.error('Error in mission-created webhook', { error: error instanceof Error ? error.message : String(error) }); return NextResponse.json( { error: 'Failed to update mission', details: error instanceof Error ? error.message : String(error) }, { status: 500 } ); } }