NeahNew/lib/services/n8n-service.ts
2025-05-22 19:09:11 +02:00

158 lines
5.5 KiB
TypeScript

import { env } from '@/lib/env';
export class N8nService {
private webhookUrl: string;
private rollbackWebhookUrl: string;
private apiKey: string;
constructor() {
// Use consistent webhook URLs without -test suffix
this.webhookUrl = process.env.N8N_WEBHOOK_URL || 'https://brain.slm-lab.net/webhook/mission-created';
this.rollbackWebhookUrl = process.env.N8N_ROLLBACK_WEBHOOK_URL || 'https://brain.slm-lab.net/webhook/mission-rollback';
this.apiKey = process.env.N8N_API_KEY || '';
if (!this.apiKey) {
console.error('N8N_API_KEY is not set in environment variables');
}
}
async triggerMissionCreation(data: any): Promise<any> {
try {
// Clean and validate the data
const cleanData = {
name: data.name,
oddScope: Array.isArray(data.oddScope) ? data.oddScope : [data.oddScope],
niveau: data.niveau || 'default',
intention: data.intention?.trim() || '',
missionType: data.missionType || 'default',
donneurDOrdre: data.donneurDOrdre || 'default',
projection: data.projection || 'default',
services: Array.isArray(data.services) ? data.services : [],
participation: data.participation || 'default',
profils: Array.isArray(data.profils) ? data.profils : [],
guardians: data.guardians || {},
volunteers: Array.isArray(data.volunteers) ? data.volunteers : [],
creatorId: data.creatorId,
config: {
N8N_API_KEY: this.apiKey,
MISSION_API_URL: process.env.NEXT_PUBLIC_API_URL || 'https://api.slm-lab.net/api'
}
};
// Log the cleaned data
console.log('Sending cleaned data to n8n:', {
name: cleanData.name,
creatorId: cleanData.creatorId,
oddScope: cleanData.oddScope,
niveau: cleanData.niveau,
intention: cleanData.intention?.substring(0, 100) + '...', // Log first 100 chars
missionType: cleanData.missionType,
donneurDOrdre: cleanData.donneurDOrdre,
projection: cleanData.projection,
services: cleanData.services,
participation: cleanData.participation,
profils: cleanData.profils,
hasGuardians: !!cleanData.guardians,
volunteersCount: cleanData.volunteers.length,
hasConfig: !!cleanData.config,
configKeys: cleanData.config ? Object.keys(cleanData.config) : []
});
console.log('Using webhook URL:', this.webhookUrl);
console.log('API key present:', !!this.apiKey);
const response = await fetch(this.webhookUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-api-key': this.apiKey
},
body: JSON.stringify(cleanData),
});
console.log('Webhook response status:', response.status);
console.log('Webhook response headers:', Object.fromEntries(response.headers.entries()));
if (!response.ok) {
const errorText = await response.text();
console.error('Webhook error response:', errorText);
// Try to parse the error response as JSON for more details
try {
const errorJson = JSON.parse(errorText);
console.error('Parsed error response:', errorJson);
} catch (e) {
console.error('Error response is not JSON');
}
throw new Error(`HTTP error! status: ${response.status}, body: ${errorText}`);
}
const responseText = await response.text();
console.log('Raw response from n8n:', responseText);
// Try to parse the response as JSON
try {
const result = JSON.parse(responseText);
console.log('Parsed workflow result:', JSON.stringify(result, null, 2));
return {
success: true,
results: result
};
} catch (parseError) {
console.log('Response is not JSON, treating as workflow trigger confirmation');
return {
success: true,
results: {
logoUrl: null,
leantimeProjectId: null,
outlineCollectionId: null,
rocketChatChannelId: null,
giteaRepositoryUrl: null
}
};
}
} catch (error) {
console.error('Error triggering n8n workflow:', error);
return {
success: false,
error: error instanceof Error ? error.message : 'Unknown error'
};
}
}
async triggerMissionRollback(data: any): Promise<any> {
try {
console.log('Triggering n8n rollback workflow with data:', JSON.stringify(data, null, 2));
console.log('Using rollback webhook URL:', this.rollbackWebhookUrl);
console.log('API key present:', !!this.apiKey);
const response = await fetch(this.rollbackWebhookUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-api-key': this.apiKey
},
body: JSON.stringify(data),
});
if (!response.ok) {
const errorText = await response.text();
console.error('Rollback webhook error response:', errorText);
throw new Error(`HTTP error! status: ${response.status}, body: ${errorText}`);
}
const result = await response.json();
console.log('Received response from n8n rollback:', JSON.stringify(result, null, 2));
return {
success: true,
results: result
};
} catch (error) {
console.error('Error triggering n8n rollback workflow:', error);
return {
success: false,
error: error instanceof Error ? error.message : 'Unknown error'
};
}
}
}