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, gitRepoUrl: body.gitRepoUrl, leantimeProjectId: body.leantimeProjectId, documentationCollectionId: body.documentationCollectionId, rocketchatChannelId: body.rocketchatChannelId, gitRepoUrlType: typeof body.gitRepoUrl, rocketchatChannelIdType: typeof body.rocketchatChannelId, }); // 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; } = {}; // Helper function to check if a value is valid const isValidValue = (value: any, type?: 'gitea' | 'outline' | 'rocketchat' | 'leantime'): boolean => { if (value === null || value === undefined) return false; if (typeof value === 'string') { const trimmed = value.trim(); if (trimmed === '' || trimmed === '0' || trimmed === 'null' || trimmed === 'undefined') return false; // Additional validation based on type if (type === 'gitea') { // Reject Outline collection paths (they start with /collection/) if (trimmed.startsWith('/collection/')) return false; // Reject if it doesn't look like a URL or repo path if (!trimmed.includes('http') && !trimmed.includes('/') && trimmed.length < 3) return false; } if (type === 'outline') { // Outline IDs should be UUIDs or paths if (trimmed.startsWith('/collection/')) return true; // This is valid for Outline } if (type === 'rocketchat') { // RocketChat channel IDs should be alphanumeric strings if (trimmed.length < 3) return false; } return true; } if (typeof value === 'number') return value !== 0; return true; }; // Mapper les champs N8N vers notre schéma Prisma // Vérifier que les valeurs ne sont pas des chaînes vides, "0", "null", "undefined", etc. // ET vérifier qu'elles correspondent au bon type (pas de mélange Gitea/Outline) if (body.gitRepoUrl !== undefined) { const isValid = isValidValue(body.gitRepoUrl, 'gitea'); updateData.giteaRepositoryUrl = isValid ? body.gitRepoUrl : null; logger.debug('Updating giteaRepositoryUrl', { hasUrl: !!updateData.giteaRepositoryUrl, value: body.gitRepoUrl, isValid, isOutlinePath: typeof body.gitRepoUrl === 'string' && body.gitRepoUrl.trim().startsWith('/collection/') }); } if (body.leantimeProjectId !== undefined) { // N8N peut retourner un number, on le convertit en string const projectId = body.leantimeProjectId ? String(body.leantimeProjectId).trim() : ''; const isValid = isValidValue(projectId, 'leantime'); updateData.leantimeProjectId = isValid ? projectId : null; logger.debug('Updating leantimeProjectId', { hasId: !!updateData.leantimeProjectId, value: body.leantimeProjectId, isValid }); } if (body.documentationCollectionId !== undefined) { const isValid = isValidValue(body.documentationCollectionId, 'outline'); updateData.outlineCollectionId = isValid ? body.documentationCollectionId : null; logger.debug('Updating outlineCollectionId', { hasId: !!updateData.outlineCollectionId, value: body.documentationCollectionId, isValid }); } if (body.rocketchatChannelId !== undefined) { const isValid = isValidValue(body.rocketchatChannelId, 'rocketchat'); updateData.rocketChatChannelId = isValid ? body.rocketchatChannelId : null; logger.debug('Updating rocketChatChannelId', { hasId: !!updateData.rocketChatChannelId, value: body.rocketchatChannelId, isValid, valueType: typeof body.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 } ); } }