W n8n attention vm

This commit is contained in:
alma 2025-05-24 20:32:46 +02:00
parent 7bcaf2fc4c
commit 486a8db3a8
2 changed files with 58 additions and 118 deletions

View File

@ -209,7 +209,7 @@ export async function POST(request: Request) {
}, { status: 400 }); }, { status: 400 });
} }
// Step 1: Upload files to Minio if present // Step 1: Upload logo to Minio if present
let logoPath = null; let logoPath = null;
if (body.logo?.data) { if (body.logo?.data) {
try { try {
@ -230,55 +230,7 @@ export async function POST(request: Request) {
} }
} }
// Upload attachments if present // Step 2: Create mission in database with logo path
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: Trigger n8n workflow
try {
console.log('=== Starting N8N Workflow ===');
const n8nService = new N8nService();
// Prepare data for n8n
const n8nData = {
...body,
creatorId: userId,
logoPath, // Add the uploaded logo path
attachmentPaths, // Add the uploaded attachment paths
config: {
N8N_API_KEY: process.env.N8N_API_KEY,
MISSION_API_URL: process.env.NEXT_PUBLIC_API_URL
}
};
console.log('Sending to N8N:', JSON.stringify(n8nData, null, 2));
// Trigger n8n workflow
const workflowResult = await n8nService.triggerMissionCreation(n8nData);
console.log('N8N Workflow Result:', JSON.stringify(workflowResult, null, 2));
if (!workflowResult.success) {
throw new Error(workflowResult.error || 'N8N workflow failed');
}
// Step 3: Create mission in database
try {
const missionData = { const missionData = {
name: body.name, name: body.name,
oddScope: body.oddScope, oddScope: body.oddScope,
@ -292,11 +244,6 @@ export async function POST(request: Request) {
participation: body.participation, participation: body.participation,
creatorId: userId, creatorId: userId,
logo: logoPath, 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)); console.log('Creating mission with data:', JSON.stringify(missionData, null, 2));
@ -321,17 +268,29 @@ export async function POST(request: Request) {
})); }));
} }
for (const attachmentPath of attachmentPaths) { // Step 3: Trigger n8n workflow only after mission is created and logo is uploaded
const finalAttachmentPath = attachmentPath.replace('temp', mission.id); try {
await s3Client.send(new CopyObjectCommand({ console.log('=== Starting N8N Workflow ===');
Bucket: 'missions', const n8nService = new N8nService();
CopySource: `missions/${attachmentPath}`,
Key: finalAttachmentPath.replace('missions/', '') // Prepare data for n8n
})); const n8nData = {
await s3Client.send(new DeleteObjectCommand({ ...body,
Bucket: 'missions', creatorId: userId,
Key: attachmentPath.replace('missions/', '') 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
}
};
console.log('Sending to N8N:', JSON.stringify(n8nData, null, 2));
// Trigger n8n workflow
const workflowResult = await n8nService.triggerMissionCreation(n8nData);
console.log('N8N Workflow Result:', JSON.stringify(workflowResult, null, 2));
if (!workflowResult.success) {
throw new Error(workflowResult.error || 'N8N workflow failed');
} }
return NextResponse.json({ return NextResponse.json({
@ -339,10 +298,6 @@ export async function POST(request: Request) {
mission, mission,
message: 'Mission created successfully with all integrations' 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');
}
} catch (n8nError) { } catch (n8nError) {
console.error('Error with n8n service:', n8nError); console.error('Error with n8n service:', n8nError);
throw new Error('Failed to create mission resources'); throw new Error('Failed to create mission resources');

View File

@ -399,7 +399,7 @@ export function MissionsAdminPanel() {
setIsSubmitting(true); setIsSubmitting(true);
try { try {
// Prepare the mission data without files // Prepare the mission data with logo
const formattedData = { const formattedData = {
name: missionData.name || '', name: missionData.name || '',
oddScope: (Array.isArray(missionData.oddScope) ? missionData.oddScope : [missionData.oddScope]).filter(Boolean) as string[], oddScope: (Array.isArray(missionData.oddScope) ? missionData.oddScope : [missionData.oddScope]).filter(Boolean) as string[],
@ -417,10 +417,15 @@ export function MissionsAdminPanel() {
'gardien-memoire': gardienDeLaMemoire || '' 'gardien-memoire': gardienDeLaMemoire || ''
}, },
volunteers: (volontaires || []).filter(Boolean) as string[], 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 // Send to API
const createResponse = await fetch('/api/missions', { const response = await fetch('/api/missions', {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
@ -428,32 +433,12 @@ export function MissionsAdminPanel() {
body: JSON.stringify(formattedData), body: JSON.stringify(formattedData),
}); });
const responseData = await createResponse.json(); if (!response.ok) {
const errorData = await response.json();
if (!createResponse.ok) { throw new Error(errorData.error || 'Failed to create mission');
throw new Error(responseData.error || 'Failed to create mission');
} }
// If we have a logo, upload it to Minio const data = await response.json();
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);
}
}
toast({ toast({
title: "Mission créée avec succès", title: "Mission créée avec succès",