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,28 +230,45 @@ export async function POST(request: Request) {
} }
} }
// Upload attachments if present // Step 2: Create mission in database with logo path
const attachmentPaths = []; const missionData = {
if (body.attachments?.length > 0) { name: body.name,
for (const attachment of body.attachments) { oddScope: body.oddScope,
try { niveau: body.niveau,
const base64Data = attachment.data.split(',')[1]; intention: body.intention,
const buffer = Buffer.from(base64Data, 'base64'); missionType: body.missionType,
const file = new File([buffer], attachment.name, { type: attachment.type }); donneurDOrdre: body.donneurDOrdre,
projection: body.projection,
const result = await uploadMissionAttachment(userId, 'temp', file); services: body.services,
attachmentPaths.push(result.filePath); profils: body.profils,
uploadedFiles.push({ type: 'attachment', path: result.filePath }); participation: body.participation,
creatorId: userId,
console.log('Attachment uploaded successfully:', { path: result.filePath }); logo: logoPath,
} catch (uploadError) { };
console.error('Error uploading attachment:', uploadError);
throw new Error(`Failed to upload attachment: ${attachment.name}`); 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 { try {
console.log('=== Starting N8N Workflow ==='); console.log('=== Starting N8N Workflow ===');
const n8nService = new N8nService(); const n8nService = new N8nService();
@ -260,8 +277,7 @@ export async function POST(request: Request) {
const n8nData = { const n8nData = {
...body, ...body,
creatorId: userId, creatorId: userId,
logoPath, // Add the uploaded logo path logoPath: logoPath ? logoPath.replace('temp', mission.id) : null,
attachmentPaths, // Add the uploaded attachment paths
config: { config: {
N8N_API_KEY: process.env.N8N_API_KEY, N8N_API_KEY: process.env.N8N_API_KEY,
MISSION_API_URL: process.env.NEXT_PUBLIC_API_URL 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'); throw new Error(workflowResult.error || 'N8N workflow failed');
} }
// Step 3: Create mission in database return NextResponse.json({
try { success: true,
const missionData = { mission,
name: body.name, message: 'Mission created successfully with all integrations'
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');
}
} 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,44 +417,29 @@ 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',
}, },
body: JSON.stringify(formattedData), body: JSON.stringify(formattedData),
}); });
const responseData = await createResponse.json();
if (!createResponse.ok) { if (!response.ok) {
throw new Error(responseData.error || 'Failed to create mission'); const errorData = await response.json();
throw new Error(errorData.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",
description: "Tous les gardiens ont été assignés et la mission a été enregistrée.", description: "Tous les gardiens ont été assignés et la mission a été enregistrée.",