n8n int cleaning
This commit is contained in:
parent
45728a8e0c
commit
a4a1ac9b26
@ -5,6 +5,13 @@ import { prisma } from '@/lib/prisma';
|
|||||||
import { getPublicUrl } from '@/lib/s3';
|
import { getPublicUrl } from '@/lib/s3';
|
||||||
import { S3_CONFIG } from '@/lib/s3';
|
import { S3_CONFIG } from '@/lib/s3';
|
||||||
import { N8nService } from '@/lib/services/n8n-service';
|
import { N8nService } from '@/lib/services/n8n-service';
|
||||||
|
import { MissionUser, Prisma } from '@prisma/client';
|
||||||
|
|
||||||
|
interface MissionUserInput {
|
||||||
|
role: string;
|
||||||
|
userId: string;
|
||||||
|
missionId: string;
|
||||||
|
}
|
||||||
|
|
||||||
// Helper function to check authentication
|
// Helper function to check authentication
|
||||||
async function checkAuth(request: Request, body?: any) {
|
async function checkAuth(request: Request, body?: any) {
|
||||||
@ -143,170 +150,118 @@ 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) {
|
||||||
try {
|
try {
|
||||||
const body = await request.json();
|
const session = await getServerSession(authOptions);
|
||||||
const auth = await checkAuth(request, body);
|
if (!session?.user) {
|
||||||
if (!auth.authorized || !auth.userId) {
|
|
||||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check for existing mission with the same name
|
const body = await request.json();
|
||||||
|
const { name, oddScope, niveau, intention, missionType, donneurDOrdre, projection, services, participation, profils, guardians, volunteers } = body;
|
||||||
|
|
||||||
|
// Check if mission with same name exists
|
||||||
const existingMission = await prisma.mission.findFirst({
|
const existingMission = await prisma.mission.findFirst({
|
||||||
where: {
|
where: { name }
|
||||||
name: body.name
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
if (existingMission) {
|
if (existingMission) {
|
||||||
return NextResponse.json({
|
return NextResponse.json({ error: 'A mission with this name already exists' }, { status: 400 });
|
||||||
error: 'A mission with this name already exists',
|
|
||||||
existingMission
|
|
||||||
}, { status: 409 });
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Validate required fields
|
// Create the mission
|
||||||
if (!body.name || !body.niveau || !body.intention || !body.missionType || !body.donneurDOrdre || !body.projection) {
|
|
||||||
return NextResponse.json({
|
|
||||||
error: 'Missing required fields',
|
|
||||||
required: {
|
|
||||||
name: true,
|
|
||||||
niveau: true,
|
|
||||||
intention: true,
|
|
||||||
missionType: true,
|
|
||||||
donneurDOrdre: true,
|
|
||||||
projection: true
|
|
||||||
},
|
|
||||||
received: {
|
|
||||||
name: !!body.name,
|
|
||||||
niveau: !!body.niveau,
|
|
||||||
intention: !!body.intention,
|
|
||||||
missionType: !!body.missionType,
|
|
||||||
donneurDOrdre: !!body.donneurDOrdre,
|
|
||||||
projection: !!body.projection
|
|
||||||
}
|
|
||||||
}, { status: 400 });
|
|
||||||
}
|
|
||||||
|
|
||||||
// Create mission with default values
|
|
||||||
const mission = await prisma.mission.create({
|
const mission = await prisma.mission.create({
|
||||||
data: {
|
data: {
|
||||||
name: body.name,
|
name,
|
||||||
oddScope: body.oddScope || [],
|
oddScope,
|
||||||
niveau: body.niveau || [],
|
niveau,
|
||||||
intention: body.intention || [],
|
intention,
|
||||||
missionType: body.missionType || 'hybrid',
|
missionType,
|
||||||
donneurDOrdre: body.donneurDOrdre || [],
|
donneurDOrdre,
|
||||||
projection: body.projection || [],
|
projection,
|
||||||
services: body.services || [],
|
services,
|
||||||
profils: body.profils || [],
|
profils,
|
||||||
creatorId: auth.userId
|
creatorId: session.user.id
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// Add guardians if provided
|
// Add guardians and volunteers
|
||||||
if (body.guardians) {
|
if (guardians || volunteers) {
|
||||||
const guardianRoles = ['gardien-temps', 'gardien-parole', 'gardien-memoire'];
|
const missionUsers: MissionUserInput[] = [];
|
||||||
const guardianEntries = Object.entries(body.guardians)
|
|
||||||
.filter(([role, userId]) => guardianRoles.includes(role) && userId)
|
// Add guardians
|
||||||
.map(([role, userId]) => ({
|
if (guardians) {
|
||||||
role,
|
Object.entries(guardians).forEach(([role, userId]) => {
|
||||||
userId: userId as string,
|
if (userId) {
|
||||||
missionId: mission.id
|
missionUsers.push({
|
||||||
}));
|
role,
|
||||||
|
userId: userId as string,
|
||||||
if (guardianEntries.length > 0) {
|
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) {
|
||||||
await prisma.missionUser.createMany({
|
await prisma.missionUser.createMany({
|
||||||
data: guardianEntries
|
data: missionUsers
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Add volunteers if provided
|
|
||||||
if (body.volunteers && body.volunteers.length > 0) {
|
|
||||||
const volunteerEntries = body.volunteers.map((userId: string) => ({
|
|
||||||
role: 'volontaire',
|
|
||||||
userId,
|
|
||||||
missionId: mission.id
|
|
||||||
}));
|
|
||||||
|
|
||||||
await prisma.missionUser.createMany({
|
|
||||||
data: volunteerEntries
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
// Trigger n8n workflow
|
||||||
// Trigger the n8n workflow
|
const n8nService = new N8nService();
|
||||||
console.log('About to trigger n8n workflow with data:', {
|
console.log('About to trigger n8n workflow with data:', {
|
||||||
missionId: mission.id,
|
missionId: mission.id,
|
||||||
name: mission.name,
|
name: mission.name,
|
||||||
creatorId: auth.userId,
|
creatorId: mission.creatorId,
|
||||||
fullData: body
|
fullData: body
|
||||||
});
|
});
|
||||||
|
|
||||||
const n8nService = new N8nService();
|
|
||||||
const workflowResult = await n8nService.createMission({
|
|
||||||
...body,
|
|
||||||
missionId: mission.id,
|
|
||||||
creatorId: auth.userId
|
|
||||||
});
|
|
||||||
|
|
||||||
console.log('Received workflow result:', workflowResult);
|
const workflowResult = await n8nService.createMission({
|
||||||
|
...body,
|
||||||
|
missionId: mission.id,
|
||||||
|
creatorId: mission.creatorId
|
||||||
|
});
|
||||||
|
|
||||||
// Update mission with integration results
|
console.log('Received workflow result:', workflowResult);
|
||||||
if (workflowResult.results) {
|
|
||||||
console.log('Processing workflow results:', workflowResult.results);
|
|
||||||
const updateData: any = {};
|
|
||||||
|
|
||||||
// Update fields based on workflow results
|
|
||||||
if (workflowResult.results.gitRepo?.html_url) {
|
|
||||||
updateData.giteaRepositoryUrl = workflowResult.results.gitRepo.html_url;
|
|
||||||
}
|
|
||||||
if (workflowResult.results.leantimeProject?.result) {
|
|
||||||
updateData.leantimeProjectId = workflowResult.results.leantimeProject.result.toString();
|
|
||||||
}
|
|
||||||
if (workflowResult.results.rocketChatChannel?.channel?._id) {
|
|
||||||
updateData.rocketChatChannelId = workflowResult.results.rocketChatChannel.channel._id;
|
|
||||||
}
|
|
||||||
if (workflowResult.results.docCollection?.id) {
|
|
||||||
updateData.outlineCollectionId = workflowResult.results.docCollection.id;
|
|
||||||
}
|
|
||||||
|
|
||||||
console.log('Updating mission with integration data:', updateData);
|
// Process workflow results
|
||||||
|
const results = workflowResult.results || {};
|
||||||
|
console.log('Processing workflow results:', results);
|
||||||
|
|
||||||
// Update mission with integration data
|
// Update mission with integration data
|
||||||
await prisma.mission.update({
|
const integrationData: Prisma.MissionUncheckedUpdateInput = {
|
||||||
where: { id: mission.id },
|
leantimeProjectId: results.leantimeProjectId?.toString(),
|
||||||
data: updateData
|
outlineCollectionId: results.outlineCollectionId?.toString(),
|
||||||
});
|
rocketChatChannelId: results.rocketChatChannelId?.toString(),
|
||||||
}
|
giteaRepositoryUrl: results.giteaRepositoryUrl?.toString()
|
||||||
|
};
|
||||||
|
|
||||||
return NextResponse.json({
|
console.log('Updating mission with integration data:', integrationData);
|
||||||
success: true,
|
|
||||||
mission: {
|
const updatedMission = await prisma.mission.update({
|
||||||
id: mission.id,
|
where: { id: mission.id },
|
||||||
name: mission.name,
|
data: integrationData
|
||||||
createdAt: mission.createdAt
|
});
|
||||||
},
|
|
||||||
workflow: {
|
return NextResponse.json(updatedMission);
|
||||||
status: workflowResult.success ? 'success' : 'partial_success',
|
|
||||||
data: workflowResult,
|
|
||||||
errors: workflowResult.errors || []
|
|
||||||
}
|
|
||||||
});
|
|
||||||
} catch (workflowError) {
|
|
||||||
// If workflow fails completely, delete the mission and report failure
|
|
||||||
console.error('Workflow error:', workflowError);
|
|
||||||
await prisma.mission.delete({ where: { id: mission.id } });
|
|
||||||
|
|
||||||
return NextResponse.json({
|
|
||||||
error: 'Failed to set up external services',
|
|
||||||
details: workflowError instanceof Error ? workflowError.message : String(workflowError)
|
|
||||||
}, { status: 500 });
|
|
||||||
}
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error creating mission:', error);
|
console.error('Error creating mission:', error);
|
||||||
return NextResponse.json({
|
return NextResponse.json(
|
||||||
error: 'Internal server error',
|
{ error: 'Failed to create mission' },
|
||||||
details: error instanceof Error ? error.message : String(error)
|
{ status: 500 }
|
||||||
}, { status: 500 });
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -47,7 +47,12 @@ export class N8nService {
|
|||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
results: {
|
results: {
|
||||||
message: response.data
|
message: response.data,
|
||||||
|
// Add default empty integration results
|
||||||
|
leantimeProjectId: null,
|
||||||
|
outlineCollectionId: null,
|
||||||
|
rocketChatChannelId: null,
|
||||||
|
giteaRepositoryUrl: null
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@ -65,7 +70,18 @@ export class N8nService {
|
|||||||
throw new Error(`Workflow execution failed: ${response.data.message || 'Unknown error'}`);
|
throw new Error(`Workflow execution failed: ${response.data.message || 'Unknown error'}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
return response.data;
|
// Ensure the response has the expected structure
|
||||||
|
const result = response.data;
|
||||||
|
if (!result.results) {
|
||||||
|
result.results = {
|
||||||
|
leantimeProjectId: null,
|
||||||
|
outlineCollectionId: null,
|
||||||
|
rocketChatChannelId: null,
|
||||||
|
giteaRepositoryUrl: null
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error triggering n8n workflow:', {
|
console.error('Error triggering n8n workflow:', {
|
||||||
error: error instanceof Error ? error.message : String(error),
|
error: error instanceof Error ? error.message : String(error),
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user