This commit is contained in:
alma 2025-05-22 19:03:30 +02:00
parent 144178f760
commit 6877062826
2 changed files with 106 additions and 105 deletions

View File

@ -184,126 +184,111 @@ export async function POST(request: Request) {
return NextResponse.json({ error: 'A mission with this name already exists' }, { status: 400 }); return NextResponse.json({ error: 'A mission with this name already exists' }, { status: 400 });
} }
console.log('Creating mission in database...'); // Trigger n8n workflow first
// Create the mission const n8nService = new N8nService();
const mission = await prisma.mission.create({ const n8nData = {
data: { ...body,
name, creatorId: userId
oddScope: oddScope || 'default', };
niveau, console.log('Sending data to n8n service:', {
intention, name: n8nData.name,
missionType, creatorId: n8nData.creatorId,
donneurDOrdre, oddScope: n8nData.oddScope,
projection, niveau: n8nData.niveau,
services: Array.isArray(services) ? services.filter(Boolean) : [], intention: n8nData.intention,
profils: Array.isArray(profils) ? profils.filter(Boolean) : [], missionType: n8nData.missionType,
participation: participation || 'default', donneurDOrdre: n8nData.donneurDOrdre,
creatorId: userId projection: n8nData.projection,
} services: n8nData.services,
participation: n8nData.participation,
profils: n8nData.profils,
fullData: JSON.stringify(n8nData, null, 2)
}); });
console.log('Created mission:', JSON.stringify(mission, null, 2));
// Add guardians and volunteers
if (guardians || volunteers) {
console.log('Adding guardians and volunteers...');
const missionUsers: MissionUserInput[] = [];
// Add guardians
if (guardians) {
Object.entries(guardians).forEach(([role, userId]) => {
if (userId) {
missionUsers.push({
role,
userId: userId as string,
missionId: mission.id
});
}
});
}
// Add volunteers
if (volunteers && Array.isArray(volunteers)) {
volunteers.forEach(userId => {
if (userId) {
missionUsers.push({
role: 'volontaire',
userId,
missionId: mission.id
});
}
});
}
if (missionUsers.length > 0) {
console.log('Creating mission users:', JSON.stringify(missionUsers, null, 2));
await prisma.missionUser.createMany({
data: missionUsers
});
}
}
// Trigger n8n workflow
const n8nService = new N8nService();
console.log('About to trigger n8n workflow with data:', JSON.stringify({
missionId: mission.id,
name: mission.name,
creatorId: mission.creatorId,
fullData: body
}, null, 2));
try { try {
const workflowResult = await n8nService.triggerMissionCreation({ const workflowResult = await n8nService.triggerMissionCreation(n8nData);
missionId: mission.id,
name: mission.name,
creatorId: mission.creatorId,
oddScope: mission.oddScope,
niveau: mission.niveau,
intention: mission.intention,
missionType: mission.missionType,
donneurDOrdre: mission.donneurDOrdre,
projection: mission.projection,
services: mission.services,
participation: mission.participation,
profils: mission.profils,
config: {
N8N_API_KEY: process.env.N8N_API_KEY,
MISSION_API_URL: process.env.NEXT_PUBLIC_API_URL || 'https://api.slm-lab.net/api'
}
});
console.log('Received workflow result:', JSON.stringify(workflowResult, null, 2)); console.log('Received workflow result:', JSON.stringify(workflowResult, null, 2));
if (!workflowResult.success) { if (!workflowResult.success) {
console.error('N8n workflow failed:', workflowResult.error); console.error('N8n workflow failed:', workflowResult.error);
// Continue with mission creation even if n8n workflow fails return NextResponse.json({ error: 'Failed to create mission resources' }, { status: 500 });
return NextResponse.json(mission);
} }
// Process workflow results // Process workflow results
const results = workflowResult.results || {}; const results = workflowResult.results || {};
console.log('Processing workflow results:', JSON.stringify(results, null, 2)); console.log('Processing workflow results:', JSON.stringify(results, null, 2));
// Update mission with integration data // Now create the mission with the logo URL from n8n
const integrationData = { console.log('Creating mission in database...');
leantimeProjectId: results.leantimeProjectId?.toString(), const mission = await prisma.mission.create({
outlineCollectionId: results.outlineCollectionId?.toString(), data: {
rocketChatChannelId: results.rocketChatChannelId?.toString(), name,
giteaRepositoryUrl: results.giteaRepositoryUrl?.toString() oddScope: oddScope || 'default',
} as Prisma.MissionUpdateInput; niveau,
intention,
console.log('Updating mission with integration data:', JSON.stringify(integrationData, null, 2)); missionType,
donneurDOrdre,
const updatedMission = await prisma.mission.update({ projection,
where: { id: mission.id }, services: Array.isArray(services) ? services.filter(Boolean) : [],
data: integrationData profils: Array.isArray(profils) ? profils.filter(Boolean) : [],
participation: participation || 'default',
creatorId: userId,
logo: results.logoUrl, // Use the logo URL from n8n
leantimeProjectId: results.leantimeProjectId?.toString(),
outlineCollectionId: results.outlineCollectionId?.toString(),
rocketChatChannelId: results.rocketChatChannelId?.toString(),
giteaRepositoryUrl: results.giteaRepositoryUrl?.toString()
}
}); });
return NextResponse.json(updatedMission); console.log('Created mission:', JSON.stringify(mission, null, 2));
// Add guardians and volunteers
if (guardians || volunteers) {
console.log('Adding guardians and volunteers...');
const missionUsers: MissionUserInput[] = [];
// Add guardians
if (guardians) {
Object.entries(guardians).forEach(([role, userId]) => {
if (userId) {
missionUsers.push({
role,
userId: userId as string,
missionId: mission.id
});
}
});
}
// Add volunteers
if (volunteers && Array.isArray(volunteers)) {
volunteers.forEach(userId => {
if (userId) {
missionUsers.push({
role: 'volontaire',
userId,
missionId: mission.id
});
}
});
}
if (missionUsers.length > 0) {
console.log('Creating mission users:', JSON.stringify(missionUsers, null, 2));
await prisma.missionUser.createMany({
data: missionUsers
});
}
}
return NextResponse.json(mission);
} catch (error) { } catch (error) {
console.error('Error in n8n workflow:', error); console.error('Error in n8n workflow:', error);
// Return the mission even if n8n workflow fails return NextResponse.json(
return NextResponse.json(mission); { error: 'Failed to create mission resources', details: error instanceof Error ? error.message : String(error) },
{ status: 500 }
);
} }
} catch (error) { } catch (error) {
console.error('Error creating mission:', error); console.error('Error creating mission:', error);

View File

@ -18,6 +18,22 @@ export class N8nService {
async triggerMissionCreation(data: any): Promise<any> { async triggerMissionCreation(data: any): Promise<any> {
try { try {
// Log the incoming data
console.log('Incoming data to n8n service:', {
hasMissionId: !!data.missionId,
hasName: !!data.name,
hasCreatorId: !!data.creatorId,
oddScope: data.oddScope,
niveau: data.niveau,
intention: data.intention,
missionType: data.missionType,
donneurDOrdre: data.donneurDOrdre,
projection: data.projection,
services: data.services,
participation: data.participation,
profils: data.profils
});
// Add API key and default values to the data // Add API key and default values to the data
const dataWithDefaults = { const dataWithDefaults = {
...data, ...data,
@ -38,10 +54,10 @@ export class N8nService {
hasConfig: !!dataWithDefaults.config, hasConfig: !!dataWithDefaults.config,
configKeys: dataWithDefaults.config ? Object.keys(dataWithDefaults.config) : [], configKeys: dataWithDefaults.config ? Object.keys(dataWithDefaults.config) : [],
apiKeyPresent: !!dataWithDefaults.config?.N8N_API_KEY, apiKeyPresent: !!dataWithDefaults.config?.N8N_API_KEY,
apiUrlPresent: !!dataWithDefaults.config?.MISSION_API_URL apiUrlPresent: !!dataWithDefaults.config?.MISSION_API_URL,
fullData: JSON.stringify(dataWithDefaults, null, 2)
}); });
console.log('Triggering n8n workflow with data:', JSON.stringify(dataWithDefaults, null, 2));
console.log('Using webhook URL:', this.webhookUrl); console.log('Using webhook URL:', this.webhookUrl);
console.log('API key present:', !!this.apiKey); console.log('API key present:', !!this.apiKey);