W n8n
This commit is contained in:
parent
355bc5424f
commit
25157439c3
File diff suppressed because one or more lines are too long
275
My_workflow_41.json
Normal file
275
My_workflow_41.json
Normal file
File diff suppressed because one or more lines are too long
@ -2,10 +2,30 @@ import { NextResponse } from 'next/server';
|
|||||||
import { getServerSession } from 'next-auth';
|
import { getServerSession } from 'next-auth';
|
||||||
import { authOptions } from "@/app/api/auth/options";
|
import { authOptions } from "@/app/api/auth/options";
|
||||||
import { prisma } from '@/lib/prisma';
|
import { prisma } from '@/lib/prisma';
|
||||||
import { getPublicUrl } 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';
|
import { Prisma } from '@prisma/client';
|
||||||
|
|
||||||
|
// Types
|
||||||
|
interface MissionCreateInput {
|
||||||
|
name: string;
|
||||||
|
oddScope?: string[];
|
||||||
|
niveau: string;
|
||||||
|
intention: string;
|
||||||
|
missionType: string;
|
||||||
|
donneurDOrdre: string;
|
||||||
|
projection: string;
|
||||||
|
services?: string[];
|
||||||
|
participation?: string;
|
||||||
|
profils?: string[];
|
||||||
|
guardians?: Record<string, string>;
|
||||||
|
volunteers?: string[];
|
||||||
|
logo?: string | null;
|
||||||
|
leantimeProjectId?: string;
|
||||||
|
documentationCollectionId?: string;
|
||||||
|
rocketchatChannelId?: string;
|
||||||
|
gitRepoUrl?: string;
|
||||||
|
penpotProjectId?: string;
|
||||||
|
}
|
||||||
|
|
||||||
interface MissionUserInput {
|
interface MissionUserInput {
|
||||||
role: string;
|
role: string;
|
||||||
@ -15,41 +35,19 @@ interface MissionUserInput {
|
|||||||
|
|
||||||
// Helper function to check authentication
|
// Helper function to check authentication
|
||||||
async function checkAuth(request: Request) {
|
async function checkAuth(request: Request) {
|
||||||
// Check for API key in headers first
|
|
||||||
const apiKey = request.headers.get('x-api-key');
|
const apiKey = request.headers.get('x-api-key');
|
||||||
console.log('Received API key from headers:', apiKey);
|
if (apiKey === process.env.N8N_API_KEY) {
|
||||||
|
|
||||||
// If no API key in headers, try to get it from the request body
|
|
||||||
let bodyApiKey = null;
|
|
||||||
if (request.method === 'POST') {
|
|
||||||
const body = await request.clone().json();
|
|
||||||
bodyApiKey = body?.config?.N8N_API_KEY;
|
|
||||||
console.log('Received API key from body:', bodyApiKey);
|
|
||||||
}
|
|
||||||
|
|
||||||
const receivedApiKey = apiKey || bodyApiKey;
|
|
||||||
console.log('Final API key used:', receivedApiKey);
|
|
||||||
console.log('Expected API key:', process.env.N8N_API_KEY);
|
|
||||||
console.log('API key match:', receivedApiKey === process.env.N8N_API_KEY);
|
|
||||||
|
|
||||||
if (receivedApiKey === process.env.N8N_API_KEY) {
|
|
||||||
return { authorized: true, userId: 'system' };
|
return { authorized: true, userId: 'system' };
|
||||||
}
|
}
|
||||||
|
|
||||||
// If no API key, check for session
|
|
||||||
const session = await getServerSession(authOptions);
|
const session = await getServerSession(authOptions);
|
||||||
if (!session?.user?.id) {
|
if (!session?.user?.id) {
|
||||||
console.error('Unauthorized access attempt:', {
|
|
||||||
url: request.url,
|
|
||||||
method: request.method,
|
|
||||||
headers: Object.fromEntries(request.headers)
|
|
||||||
});
|
|
||||||
return { authorized: false, userId: null };
|
return { authorized: false, userId: null };
|
||||||
}
|
}
|
||||||
return { authorized: true, userId: session.user.id };
|
return { authorized: true, userId: session.user.id };
|
||||||
}
|
}
|
||||||
|
|
||||||
// GET endpoint to list missions with filters
|
// GET endpoint to list missions
|
||||||
export async function GET(request: Request) {
|
export async function GET(request: Request) {
|
||||||
try {
|
try {
|
||||||
const { authorized, userId } = await checkAuth(request);
|
const { authorized, userId } = await checkAuth(request);
|
||||||
@ -61,11 +59,10 @@ export async function GET(request: Request) {
|
|||||||
const limit = Number(searchParams.get('limit') || '10');
|
const limit = Number(searchParams.get('limit') || '10');
|
||||||
const offset = Number(searchParams.get('offset') || '0');
|
const offset = Number(searchParams.get('offset') || '0');
|
||||||
const search = searchParams.get('search');
|
const search = searchParams.get('search');
|
||||||
|
const name = searchParams.get('name');
|
||||||
|
|
||||||
// Build query conditions
|
const where: Prisma.MissionWhereInput = {};
|
||||||
const where: any = {};
|
|
||||||
|
|
||||||
// Add search filter if provided
|
|
||||||
if (search) {
|
if (search) {
|
||||||
where.OR = [
|
where.OR = [
|
||||||
{ name: { contains: search, mode: 'insensitive' } },
|
{ name: { contains: search, mode: 'insensitive' } },
|
||||||
@ -73,24 +70,16 @@ export async function GET(request: Request) {
|
|||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get missions with basic info
|
if (name) {
|
||||||
const missions = await (prisma as any).mission.findMany({
|
where.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
const missions = await prisma.mission.findMany({
|
||||||
where,
|
where,
|
||||||
skip: offset,
|
skip: offset,
|
||||||
take: limit,
|
take: limit,
|
||||||
orderBy: { createdAt: 'desc' },
|
orderBy: { createdAt: 'desc' },
|
||||||
select: {
|
include: {
|
||||||
id: true,
|
|
||||||
name: true,
|
|
||||||
logo: true,
|
|
||||||
oddScope: true,
|
|
||||||
niveau: true,
|
|
||||||
missionType: true,
|
|
||||||
projection: true,
|
|
||||||
participation: true,
|
|
||||||
services: true,
|
|
||||||
intention: true,
|
|
||||||
createdAt: true,
|
|
||||||
creator: {
|
creator: {
|
||||||
select: {
|
select: {
|
||||||
id: true,
|
id: true,
|
||||||
@ -98,9 +87,7 @@ export async function GET(request: Request) {
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
missionUsers: {
|
missionUsers: {
|
||||||
select: {
|
include: {
|
||||||
id: true,
|
|
||||||
role: true,
|
|
||||||
user: {
|
user: {
|
||||||
select: {
|
select: {
|
||||||
id: true,
|
id: true,
|
||||||
@ -112,17 +99,10 @@ export async function GET(request: Request) {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// Get total count
|
const totalCount = await prisma.mission.count({ where });
|
||||||
const totalCount = await (prisma as any).mission.count({ where });
|
|
||||||
|
|
||||||
// Transform logo paths to public URLs
|
|
||||||
const missionsWithPublicUrls = missions.map((mission: any) => ({
|
|
||||||
...mission,
|
|
||||||
logo: mission.logo ? `/api/missions/image/${mission.logo}` : null
|
|
||||||
}));
|
|
||||||
|
|
||||||
return NextResponse.json({
|
return NextResponse.json({
|
||||||
missions: missionsWithPublicUrls,
|
missions,
|
||||||
pagination: {
|
pagination: {
|
||||||
total: totalCount,
|
total: totalCount,
|
||||||
offset,
|
offset,
|
||||||
@ -143,31 +123,17 @@ export async function POST(request: Request) {
|
|||||||
try {
|
try {
|
||||||
const { authorized, userId } = await checkAuth(request);
|
const { authorized, userId } = await checkAuth(request);
|
||||||
if (!authorized || !userId) {
|
if (!authorized || !userId) {
|
||||||
console.error('Unauthorized access attempt - no session or user');
|
|
||||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||||
}
|
}
|
||||||
|
|
||||||
const body = await request.json();
|
const requestId = request.headers.get('x-request-id');
|
||||||
console.log('Received mission creation request:', JSON.stringify(body, null, 2));
|
const body = await request.json() as MissionCreateInput;
|
||||||
|
|
||||||
const { name, oddScope, niveau, intention, missionType, donneurDOrdre, projection, services, participation, profils, guardians, volunteers } = body;
|
|
||||||
|
|
||||||
// Validate required fields
|
// Validate required fields
|
||||||
const requiredFields = {
|
const requiredFields = ['name', 'niveau', 'intention', 'missionType', 'donneurDOrdre', 'projection'];
|
||||||
name,
|
const missingFields = requiredFields.filter(field => !body[field as keyof MissionCreateInput]);
|
||||||
niveau,
|
|
||||||
intention,
|
|
||||||
missionType,
|
|
||||||
donneurDOrdre,
|
|
||||||
projection
|
|
||||||
};
|
|
||||||
|
|
||||||
const missingFields = Object.entries(requiredFields)
|
|
||||||
.filter(([_, value]) => !value)
|
|
||||||
.map(([key]) => key);
|
|
||||||
|
|
||||||
if (missingFields.length > 0) {
|
if (missingFields.length > 0) {
|
||||||
console.error('Missing required fields:', missingFields);
|
|
||||||
return NextResponse.json({
|
return NextResponse.json({
|
||||||
error: 'Missing required fields',
|
error: 'Missing required fields',
|
||||||
missingFields
|
missingFields
|
||||||
@ -176,45 +142,33 @@ export async function POST(request: Request) {
|
|||||||
|
|
||||||
// Check if mission with same name exists
|
// Check if mission with same name exists
|
||||||
const existingMission = await prisma.mission.findFirst({
|
const existingMission = await prisma.mission.findFirst({
|
||||||
where: { name },
|
where: { name: body.name }
|
||||||
select: {
|
|
||||||
id: true,
|
|
||||||
name: true,
|
|
||||||
rocketChatChannelId: true,
|
|
||||||
leantimeProjectId: true,
|
|
||||||
outlineCollectionId: true,
|
|
||||||
giteaRepositoryUrl: true
|
|
||||||
} as const
|
|
||||||
});
|
});
|
||||||
|
|
||||||
if (existingMission) {
|
if (existingMission) {
|
||||||
console.log('Mission exists, updating integration IDs:', {
|
// Update existing mission with new integration IDs
|
||||||
missionId: existingMission.id,
|
|
||||||
name: existingMission.name,
|
|
||||||
rocketchatChannelId: body.rocketchatChannelId
|
|
||||||
});
|
|
||||||
|
|
||||||
// Update the existing mission with new integration IDs
|
|
||||||
const updateData = {
|
|
||||||
rocketChatChannelId: body.rocketchatChannelId || existingMission.rocketChatChannelId,
|
|
||||||
leantimeProjectId: body.leantimeProjectId || existingMission.leantimeProjectId,
|
|
||||||
outlineCollectionId: body.documentationCollectionId || existingMission.outlineCollectionId,
|
|
||||||
giteaRepositoryUrl: body.gitRepoUrl || existingMission.giteaRepositoryUrl
|
|
||||||
} as const;
|
|
||||||
|
|
||||||
const updatedMission = await prisma.mission.update({
|
const updatedMission = await prisma.mission.update({
|
||||||
where: { id: existingMission.id },
|
where: { id: existingMission.id },
|
||||||
data: updateData as Prisma.MissionUncheckedUpdateInput
|
data: {
|
||||||
|
leantimeProjectId: body.leantimeProjectId || null,
|
||||||
|
outlineCollectionId: body.documentationCollectionId || null,
|
||||||
|
rocketChatChannelId: body.rocketchatChannelId || null,
|
||||||
|
giteaRepositoryUrl: body.gitRepoUrl || null,
|
||||||
|
penpotProjectId: body.penpotProjectId || null
|
||||||
|
} as Prisma.MissionUpdateInput
|
||||||
});
|
});
|
||||||
|
|
||||||
console.log('Updated existing mission:', JSON.stringify(updatedMission, null, 2));
|
return NextResponse.json({
|
||||||
return NextResponse.json(updatedMission);
|
message: 'Mission updated successfully',
|
||||||
|
mission: updatedMission,
|
||||||
|
isUpdate: true
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check if there's already a mission being created with this name
|
// Check for mission creation in progress
|
||||||
const missionInProgress = await prisma.mission.findFirst({
|
const missionInProgress = await prisma.mission.findFirst({
|
||||||
where: {
|
where: {
|
||||||
name,
|
name: body.name,
|
||||||
createdAt: {
|
createdAt: {
|
||||||
gte: new Date(Date.now() - 5 * 60 * 1000) // Within last 5 minutes
|
gte: new Date(Date.now() - 5 * 60 * 1000) // Within last 5 minutes
|
||||||
}
|
}
|
||||||
@ -222,7 +176,6 @@ export async function POST(request: Request) {
|
|||||||
});
|
});
|
||||||
|
|
||||||
if (missionInProgress) {
|
if (missionInProgress) {
|
||||||
console.log('Mission creation already in progress:', missionInProgress);
|
|
||||||
return NextResponse.json({
|
return NextResponse.json({
|
||||||
error: 'Mission creation already in progress',
|
error: 'Mission creation already in progress',
|
||||||
details: 'Please wait a few minutes and try again',
|
details: 'Please wait a few minutes and try again',
|
||||||
@ -230,115 +183,31 @@ export async function POST(request: Request) {
|
|||||||
}, { status: 409 });
|
}, { status: 409 });
|
||||||
}
|
}
|
||||||
|
|
||||||
// Trigger n8n workflow first
|
// Check if this is a request from n8n
|
||||||
const n8nService = new N8nService();
|
const isN8nRequest = request.headers.get('x-api-key') === process.env.N8N_API_KEY;
|
||||||
const n8nData = {
|
|
||||||
...body,
|
|
||||||
creatorId: userId
|
|
||||||
};
|
|
||||||
console.log('Sending data to n8n service:', {
|
|
||||||
name: n8nData.name,
|
|
||||||
creatorId: n8nData.creatorId,
|
|
||||||
oddScope: n8nData.oddScope,
|
|
||||||
niveau: n8nData.niveau,
|
|
||||||
intention: n8nData.intention,
|
|
||||||
missionType: n8nData.missionType,
|
|
||||||
donneurDOrdre: n8nData.donneurDOrdre,
|
|
||||||
projection: n8nData.projection,
|
|
||||||
services: n8nData.services,
|
|
||||||
participation: n8nData.participation,
|
|
||||||
profils: n8nData.profils,
|
|
||||||
fullData: JSON.stringify(n8nData, null, 2)
|
|
||||||
});
|
|
||||||
|
|
||||||
try {
|
if (!isN8nRequest) {
|
||||||
const workflowResult = await n8nService.triggerMissionCreation(n8nData);
|
// Trigger n8n workflow
|
||||||
console.log('Received workflow result:', JSON.stringify(workflowResult, null, 2));
|
const n8nService = new N8nService();
|
||||||
|
const n8nData = {
|
||||||
|
...body,
|
||||||
|
creatorId: userId,
|
||||||
|
requestId
|
||||||
|
};
|
||||||
|
|
||||||
if (!workflowResult.success) {
|
try {
|
||||||
console.error('N8n workflow failed:', workflowResult.error);
|
const workflowResult = await n8nService.triggerMissionCreation(n8nData);
|
||||||
return NextResponse.json({
|
|
||||||
error: 'Failed to create mission resources',
|
|
||||||
details: workflowResult.error,
|
|
||||||
code: 'WORKFLOW_ERROR'
|
|
||||||
}, { status: 500 });
|
|
||||||
}
|
|
||||||
|
|
||||||
// Process workflow results
|
if (!workflowResult.success) {
|
||||||
const results = workflowResult.results || {};
|
return NextResponse.json({
|
||||||
console.log('Processing workflow results:', JSON.stringify(results, null, 2));
|
error: 'Failed to create mission resources',
|
||||||
|
details: workflowResult.error,
|
||||||
// Now create the mission with the logo URL from n8n
|
code: 'WORKFLOW_ERROR'
|
||||||
console.log('Creating mission in database...');
|
}, { status: 500 });
|
||||||
const mission = await prisma.mission.create({
|
|
||||||
data: {
|
|
||||||
name,
|
|
||||||
oddScope: oddScope || ['default'],
|
|
||||||
niveau,
|
|
||||||
intention,
|
|
||||||
missionType,
|
|
||||||
donneurDOrdre,
|
|
||||||
projection,
|
|
||||||
services: Array.isArray(services) ? services.filter(Boolean) : [],
|
|
||||||
profils: Array.isArray(profils) ? profils.filter(Boolean) : [],
|
|
||||||
participation: participation || 'default',
|
|
||||||
creatorId: userId,
|
|
||||||
logo: results.logoUrl || null,
|
|
||||||
// Store integration IDs directly in the mission record
|
|
||||||
leantimeProjectId: results.leantimeProjectId?.toString() || null,
|
|
||||||
outlineCollectionId: results.outlineCollectionId?.toString() || null,
|
|
||||||
rocketChatChannelId: results.rocketChatChannelId?.toString() || null,
|
|
||||||
giteaRepositoryUrl: results.giteaRepositoryUrl?.toString() || null,
|
|
||||||
penpotProjectId: results.penpotProjectId?.toString() || null
|
|
||||||
} as Prisma.MissionUncheckedCreateInput
|
|
||||||
});
|
|
||||||
|
|
||||||
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
|
return NextResponse.json(workflowResult);
|
||||||
if (volunteers && Array.isArray(volunteers)) {
|
} catch (error) {
|
||||||
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) {
|
|
||||||
console.error('Error in n8n workflow:', error);
|
|
||||||
// If there's an error, we should clean up any resources that were created
|
|
||||||
if (error instanceof Error && error.message.includes('HTTP error! status: 500')) {
|
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{
|
{
|
||||||
error: 'Failed to create mission resources',
|
error: 'Failed to create mission resources',
|
||||||
@ -348,19 +217,79 @@ export async function POST(request: Request) {
|
|||||||
{ status: 500 }
|
{ status: 500 }
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
return NextResponse.json(
|
|
||||||
{
|
|
||||||
error: 'Failed to create mission',
|
|
||||||
details: error instanceof Error ? error.message : String(error),
|
|
||||||
code: 'MISSION_CREATION_ERROR'
|
|
||||||
},
|
|
||||||
{ status: 500 }
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Create mission directly (n8n request)
|
||||||
|
const mission = await prisma.mission.create({
|
||||||
|
data: {
|
||||||
|
name: body.name,
|
||||||
|
oddScope: body.oddScope || ['default'],
|
||||||
|
niveau: body.niveau,
|
||||||
|
intention: body.intention,
|
||||||
|
missionType: body.missionType,
|
||||||
|
donneurDOrdre: body.donneurDOrdre,
|
||||||
|
projection: body.projection,
|
||||||
|
services: Array.isArray(body.services) ? body.services.filter(Boolean) : [],
|
||||||
|
profils: Array.isArray(body.profils) ? body.profils.filter(Boolean) : [],
|
||||||
|
participation: body.participation || 'default',
|
||||||
|
creatorId: userId,
|
||||||
|
logo: body.logo || null,
|
||||||
|
leantimeProjectId: body.leantimeProjectId || null,
|
||||||
|
outlineCollectionId: body.documentationCollectionId || null,
|
||||||
|
rocketChatChannelId: body.rocketchatChannelId || null,
|
||||||
|
giteaRepositoryUrl: body.gitRepoUrl || null,
|
||||||
|
penpotProjectId: body.penpotProjectId || null
|
||||||
|
} as Prisma.MissionUncheckedCreateInput
|
||||||
|
});
|
||||||
|
|
||||||
|
// Add guardians and volunteers
|
||||||
|
if (body.guardians || body.volunteers) {
|
||||||
|
const missionUsers: MissionUserInput[] = [];
|
||||||
|
|
||||||
|
// Add guardians
|
||||||
|
if (body.guardians) {
|
||||||
|
Object.entries(body.guardians).forEach(([role, userId]) => {
|
||||||
|
if (userId) {
|
||||||
|
missionUsers.push({
|
||||||
|
role,
|
||||||
|
userId: userId as string,
|
||||||
|
missionId: mission.id
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add volunteers
|
||||||
|
if (body.volunteers && Array.isArray(body.volunteers)) {
|
||||||
|
body.volunteers.forEach(userId => {
|
||||||
|
if (userId) {
|
||||||
|
missionUsers.push({
|
||||||
|
role: 'volontaire',
|
||||||
|
userId,
|
||||||
|
missionId: mission.id
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (missionUsers.length > 0) {
|
||||||
|
await prisma.missionUser.createMany({
|
||||||
|
data: missionUsers
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return NextResponse.json({
|
||||||
|
message: 'Mission created successfully',
|
||||||
|
mission
|
||||||
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error creating mission:', error);
|
console.error('Error creating mission:', error);
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{ error: 'Failed to create mission', details: error instanceof Error ? error.message : String(error) },
|
{
|
||||||
|
error: 'Failed to create mission',
|
||||||
|
details: error instanceof Error ? error.message : String(error)
|
||||||
|
},
|
||||||
{ status: 500 }
|
{ status: 500 }
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user