From 486a8db3a8d6b6c78d8081dc043a9f97dcab90b7 Mon Sep 17 00:00:00 2001 From: alma Date: Sat, 24 May 2025 20:32:46 +0200 Subject: [PATCH] W n8n attention vm --- app/api/missions/route.ts | 133 ++++++------------- components/missions/missions-admin-panel.tsx | 43 ++---- 2 files changed, 58 insertions(+), 118 deletions(-) diff --git a/app/api/missions/route.ts b/app/api/missions/route.ts index abee43ff..8ee19131 100644 --- a/app/api/missions/route.ts +++ b/app/api/missions/route.ts @@ -209,7 +209,7 @@ export async function POST(request: Request) { }, { status: 400 }); } - // Step 1: Upload files to Minio if present + // Step 1: Upload logo to Minio if present let logoPath = null; if (body.logo?.data) { try { @@ -230,28 +230,45 @@ export async function POST(request: Request) { } } - // Upload attachments if present - const attachmentPaths = []; - if (body.attachments?.length > 0) { - for (const attachment of body.attachments) { - try { - const base64Data = attachment.data.split(',')[1]; - const buffer = Buffer.from(base64Data, 'base64'); - const file = new File([buffer], attachment.name, { type: attachment.type }); - - const result = await uploadMissionAttachment(userId, 'temp', file); - attachmentPaths.push(result.filePath); - uploadedFiles.push({ type: 'attachment', path: result.filePath }); - - console.log('Attachment uploaded successfully:', { path: result.filePath }); - } catch (uploadError) { - console.error('Error uploading attachment:', uploadError); - throw new Error(`Failed to upload attachment: ${attachment.name}`); - } - } + // Step 2: Create mission in database with logo path + 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: logoPath, + }; + + console.log('Creating mission with data:', JSON.stringify(missionData, null, 2)); + + const mission = await prisma.mission.create({ + data: missionData + }); + + console.log('Mission created successfully:', JSON.stringify(mission, null, 2)); + + // Move uploaded files to final location + if (logoPath) { + const finalLogoPath = logoPath.replace('temp', mission.id); + await s3Client.send(new CopyObjectCommand({ + Bucket: 'missions', + CopySource: `missions/${logoPath}`, + Key: finalLogoPath.replace('missions/', '') + })); + await s3Client.send(new DeleteObjectCommand({ + Bucket: 'missions', + Key: logoPath.replace('missions/', '') + })); } - // Step 2: Trigger n8n workflow + // Step 3: Trigger n8n workflow only after mission is created and logo is uploaded try { console.log('=== Starting N8N Workflow ==='); const n8nService = new N8nService(); @@ -260,8 +277,7 @@ export async function POST(request: Request) { const n8nData = { ...body, creatorId: userId, - logoPath, // Add the uploaded logo path - attachmentPaths, // Add the uploaded attachment paths + logoPath: logoPath ? logoPath.replace('temp', mission.id) : null, config: { N8N_API_KEY: process.env.N8N_API_KEY, MISSION_API_URL: process.env.NEXT_PUBLIC_API_URL @@ -277,72 +293,11 @@ export async function POST(request: Request) { throw new Error(workflowResult.error || 'N8N workflow failed'); } - // Step 3: Create mission in database - 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: logoPath, - leantimeProjectId: workflowResult.leantimeProjectId, - outlineCollectionId: workflowResult.outlineCollectionId, - rocketChatChannelId: workflowResult.rocketChatChannelId, - giteaRepositoryUrl: workflowResult.giteaRepositoryUrl, - penpotProjectId: workflowResult.penpotProjectId - }; - - console.log('Creating mission with data:', JSON.stringify(missionData, null, 2)); - - const mission = await prisma.mission.create({ - data: missionData - }); - - console.log('Mission created successfully:', JSON.stringify(mission, null, 2)); - - // Move uploaded files to final location - if (logoPath) { - const finalLogoPath = logoPath.replace('temp', mission.id); - await s3Client.send(new CopyObjectCommand({ - Bucket: 'missions', - CopySource: `missions/${logoPath}`, - Key: finalLogoPath.replace('missions/', '') - })); - await s3Client.send(new DeleteObjectCommand({ - Bucket: 'missions', - Key: logoPath.replace('missions/', '') - })); - } - - for (const attachmentPath of attachmentPaths) { - const finalAttachmentPath = attachmentPath.replace('temp', mission.id); - await s3Client.send(new CopyObjectCommand({ - Bucket: 'missions', - CopySource: `missions/${attachmentPath}`, - Key: finalAttachmentPath.replace('missions/', '') - })); - await s3Client.send(new DeleteObjectCommand({ - Bucket: 'missions', - Key: attachmentPath.replace('missions/', '') - })); - } - - return NextResponse.json({ - success: true, - mission, - message: 'Mission created successfully with all integrations' - }); - } catch (dbError) { - console.error('Database error creating mission:', dbError); - throw new Error('Failed to create mission in database'); - } + return NextResponse.json({ + success: true, + mission, + message: 'Mission created successfully with all integrations' + }); } catch (n8nError) { console.error('Error with n8n service:', n8nError); throw new Error('Failed to create mission resources'); diff --git a/components/missions/missions-admin-panel.tsx b/components/missions/missions-admin-panel.tsx index 1cf38c29..6974cfee 100644 --- a/components/missions/missions-admin-panel.tsx +++ b/components/missions/missions-admin-panel.tsx @@ -399,7 +399,7 @@ export function MissionsAdminPanel() { setIsSubmitting(true); try { - // Prepare the mission data without files + // Prepare the mission data with logo const formattedData = { name: missionData.name || '', oddScope: (Array.isArray(missionData.oddScope) ? missionData.oddScope : [missionData.oddScope]).filter(Boolean) as string[], @@ -417,44 +417,29 @@ export function MissionsAdminPanel() { 'gardien-memoire': gardienDeLaMemoire || '' }, volunteers: (volontaires || []).filter(Boolean) as string[], + logo: missionData.logo ? { + data: missionData.logo, + name: 'logo.png', + type: 'image/png' + } : null }; - // Create the mission first to get the mission ID - const createResponse = await fetch('/api/missions', { + // Send to API + const response = await fetch('/api/missions', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(formattedData), }); - - const responseData = await createResponse.json(); - if (!createResponse.ok) { - throw new Error(responseData.error || 'Failed to create mission'); + if (!response.ok) { + const errorData = await response.json(); + throw new Error(errorData.error || 'Failed to create mission'); } - - // If we have a logo, upload it to Minio - if (missionData.logo) { - try { - const logoFormData = new FormData(); - logoFormData.append('missionId', responseData.mission.id); - logoFormData.append('type', 'logo'); - logoFormData.append('file', missionData.logo); - - const logoUploadResponse = await fetch('/api/missions/upload', { - method: 'POST', - body: logoFormData, - }); - - if (!logoUploadResponse.ok) { - console.warn('Failed to upload logo:', await logoUploadResponse.text()); - } - } catch (error) { - console.error('Error uploading logo:', error); - } - } - + + const data = await response.json(); + toast({ title: "Mission créée avec succès", description: "Tous les gardiens ont été assignés et la mission a été enregistrée.",