W n8n attention vm

This commit is contained in:
alma 2025-05-24 19:50:15 +02:00
parent 85c3eeceac
commit 6274f3a401
2 changed files with 155 additions and 122 deletions

View File

@ -4,6 +4,9 @@ import { authOptions } from "@/app/api/auth/options";
import { prisma } from '@/lib/prisma'; import { prisma } from '@/lib/prisma';
import { N8nService } from '@/lib/services/n8n-service'; import { N8nService } from '@/lib/services/n8n-service';
import { Prisma } from '@prisma/client'; import { Prisma } from '@prisma/client';
import { s3Client } from '@/lib/s3';
import { CopyObjectCommand, DeleteObjectCommand } from '@aws-sdk/client-s3';
import { uploadMissionLogo, uploadMissionAttachment } from '@/lib/mission-uploads';
// Types // Types
interface MissionCreateInput { interface MissionCreateInput {
@ -186,6 +189,8 @@ export async function GET(request: Request) {
// POST endpoint to create a new mission // POST endpoint to create a new mission
export async function POST(request: Request) { export async function POST(request: Request) {
let uploadedFiles: { type: 'logo' | 'attachment', path: string }[] = [];
try { try {
console.log('=== Mission Creation Started ==='); console.log('=== Mission Creation Started ===');
const { authorized, userId } = await checkAuth(request); const { authorized, userId } = await checkAuth(request);
@ -204,11 +209,49 @@ export async function POST(request: Request) {
}, { status: 400 }); }, { status: 400 });
} }
// Check if this is a request from n8n // Step 1: Upload files to Minio if present
const isN8nRequest = request.headers.get('x-api-key') === process.env.N8N_API_KEY; let logoPath = null;
console.log('Is N8N request:', isN8nRequest); if (body.logo?.data) {
try {
// Convert base64 to File object
const base64Data = body.logo.data.split(',')[1];
const buffer = Buffer.from(base64Data, 'base64');
const file = new File([buffer], body.logo.name || 'logo.png', { type: body.logo.type || 'image/png' });
if (!isN8nRequest) { // Upload logo
const { filePath } = await uploadMissionLogo(userId, 'temp', file);
logoPath = filePath;
uploadedFiles.push({ type: 'logo', path: filePath });
console.log('Logo uploaded successfully:', { logoPath });
} catch (uploadError) {
console.error('Error uploading logo:', uploadError);
throw new Error('Failed to upload logo');
}
}
// 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: Trigger n8n workflow
try { try {
console.log('=== Starting N8N Workflow ==='); console.log('=== Starting N8N Workflow ===');
const n8nService = new N8nService(); const n8nService = new N8nService();
@ -217,6 +260,8 @@ export async function POST(request: Request) {
const n8nData = { const n8nData = {
...body, ...body,
creatorId: userId, creatorId: userId,
logoPath, // Add the uploaded logo path
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
@ -224,49 +269,16 @@ export async function POST(request: Request) {
}; };
console.log('Sending to N8N:', JSON.stringify(n8nData, null, 2)); console.log('Sending to N8N:', JSON.stringify(n8nData, null, 2));
// Trigger n8n workflow first // Trigger n8n workflow
const workflowResult = await n8nService.triggerMissionCreation(n8nData); const workflowResult = await n8nService.triggerMissionCreation(n8nData);
console.log('N8N Workflow Result:', JSON.stringify(workflowResult, null, 2)); console.log('N8N Workflow Result:', JSON.stringify(workflowResult, null, 2));
if (!workflowResult.success) { if (!workflowResult.success) {
console.error('N8N workflow failed:', workflowResult.error); throw new Error(workflowResult.error || 'N8N workflow failed');
return NextResponse.json({
error: 'Failed to create mission resources',
details: workflowResult.error
}, { status: 500 });
} }
// Only create mission in database after n8n succeeds // Step 3: Create mission in database
try { try {
// Extract logo path from workflow result
let logoPath = null;
console.log('Full workflow result:', JSON.stringify(workflowResult, null, 2));
if (workflowResult.results && Array.isArray(workflowResult.results)) {
const firstResult = workflowResult.results[0];
console.log('First result from workflow:', JSON.stringify(firstResult, null, 2));
// Check if the result is HTML (error case)
if (typeof firstResult === 'string' && firstResult.includes('<!DOCTYPE html>')) {
console.error('Received HTML response instead of JSON:', firstResult);
return NextResponse.json({
error: 'Invalid response from workflow',
details: 'Received HTML instead of JSON data'
}, { status: 500 });
}
// Get logo path from the nested structure
if (firstResult?.integrationResults?.uploadResults?.logoPath) {
logoPath = firstResult.integrationResults.uploadResults.logoPath;
console.log('Extracted logo path from uploadResults:', logoPath);
} else if (firstResult?.logoPath) {
logoPath = firstResult.logoPath;
console.log('Extracted logo path from root:', logoPath);
} else {
console.log('No logo path found in result:', firstResult);
}
}
const missionData = { const missionData = {
name: body.name, name: body.name,
oddScope: body.oddScope, oddScope: body.oddScope,
@ -279,7 +291,12 @@ export async function POST(request: Request) {
profils: body.profils, profils: body.profils,
participation: body.participation, participation: body.participation,
creatorId: userId, creatorId: userId,
logo: logoPath ? `missions/${logoPath}` : null 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));
@ -290,6 +307,33 @@ export async function POST(request: Request) {
console.log('Mission created successfully:', JSON.stringify(mission, null, 2)); 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({ return NextResponse.json({
success: true, success: true,
mission, mission,
@ -297,52 +341,28 @@ export async function POST(request: Request) {
}); });
} catch (dbError) { } catch (dbError) {
console.error('Database error creating mission:', dbError); console.error('Database error creating mission:', dbError);
return NextResponse.json({ throw new Error('Failed to create mission in database');
error: 'Failed to create mission in database',
details: dbError instanceof Error ? dbError.message : String(dbError)
}, { status: 500 });
} }
} catch (n8nError) { } catch (n8nError) {
console.error('Error with n8n service:', n8nError); console.error('Error with n8n service:', n8nError);
return NextResponse.json({ throw new Error('Failed to create mission resources');
error: 'Failed to create mission resources',
details: n8nError instanceof Error ? n8nError.message : String(n8nError)
}, { status: 500 });
}
} else {
console.log('=== Handling N8N Callback ===');
console.log('N8N callback body:', JSON.stringify(body, null, 2));
// Handle n8n callback - update mission with integration IDs
try {
const mission = await prisma.mission.update({
where: { id: body.missionId },
data: {
leantimeProjectId: body.leantimeProjectId ? String(body.leantimeProjectId) : null,
outlineCollectionId: body.outlineCollectionId || null,
rocketChatChannelId: body.rocketChatChannelId || null,
giteaRepositoryUrl: body.giteaRepositoryUrl || null,
penpotProjectId: body.penpotProjectId || null,
logo: body.logoPath ? `missions/${body.logoPath}` : null // Add logo path update here
} as Prisma.MissionUpdateInput
});
console.log('Mission updated with integrations:', JSON.stringify(mission, null, 2));
return NextResponse.json({
success: true,
mission,
message: 'Mission updated with integration IDs'
});
} catch (dbError) {
console.error('Database error updating mission:', dbError);
return NextResponse.json({
error: 'Failed to update mission with integration IDs',
details: dbError instanceof Error ? dbError.message : String(dbError)
}, { status: 500 });
}
} }
} catch (error) { } catch (error) {
console.error('Error in mission creation:', error); console.error('Error in mission creation:', error);
// Cleanup: Delete any uploaded files
for (const file of uploadedFiles) {
try {
await s3Client.send(new DeleteObjectCommand({
Bucket: 'missions',
Key: file.path.replace('missions/', '')
}));
console.log('Cleaned up file:', file.path);
} catch (cleanupError) {
console.error('Error cleaning up file:', file.path, cleanupError);
}
}
return NextResponse.json({ return NextResponse.json({
error: 'Failed to create mission', error: 'Failed to create mission',
details: error instanceof Error ? error.message : String(error) details: error instanceof Error ? error.message : String(error)

View File

@ -1,3 +1,16 @@
import { S3Client } from '@aws-sdk/client-s3';
// Initialize S3 client for Minio
export const s3Client = new S3Client({
region: 'us-east-1',
endpoint: 'https://dome-api.slm-lab.net',
credentials: {
accessKeyId: '4aBT4CMb7JIMMyUtp4Pl',
secretAccessKey: 'HGn39XhCIlqOjmDVzRK9MED2Fci2rYvDDgbLFElg'
},
forcePathStyle: true // Required for MinIO
});
export async function uploadMissionFile({ export async function uploadMissionFile({
missionId, missionId,
file, file,