// Service dedicated to creating n8n workflows for new users import { supabase } from "@/integrations/supabase/client"; interface N8nWorkflowPayload { name: string; nodes: any[]; connections: any; settings: any; } interface N8nWorkflowResponse { id: string; name: string; nodes: Array<{ webhookUrls?: string[]; }>; } /** * Creates a workflow in n8n for a new user * @param userEmail The email of the user who just registered * @param workflowTemplate The JSON template for the workflow * @returns The created workflow data */ export async function createN8nWorkflowForUser( userEmail: string, workflowTemplate: N8nWorkflowPayload ): Promise<{ workflowId: string; webhookUrl: string } | null> { try { console.log(`šŸš€ Criando workflow n8n para usuĆ”rio: ${userEmail}`); // Extract the username from email (part before @) const username = userEmail.split('@')[0]; // Clone the template to avoid modifying the original const modifiedTemplate = JSON.parse(JSON.stringify(workflowTemplate)); // 1. Modify the workflow name to include user email modifiedTemplate.name = modifiedTemplate.name.replace('rodrigobm10@gmail.com', userEmail); // 2. Modify webhook path in the first node to use username if (modifiedTemplate.nodes && modifiedTemplate.nodes.length > 0) { const firstNode = modifiedTemplate.nodes[0]; if (firstNode.parameters && firstNode.parameters.path) { firstNode.parameters.path = username; } } // 3. Replace all occurrences of rodrigobm10@gmail.com with user email const templateString = JSON.stringify(modifiedTemplate); const updatedTemplateString = templateString.replace(/rodrigobm10@gmail\.com/g, userEmail); const finalTemplate = JSON.parse(updatedTemplateString); console.log('šŸ“ Template modificado para usuĆ”rio:', finalTemplate.name); console.log('šŸ”§ Webhook path configurado como:', username); console.log('šŸ“‹ JSON final a ser enviado:', JSON.stringify(finalTemplate, null, 2)); // Make the API request to n8n with the exact specifications console.log('šŸ“” Fazendo requisição para:', 'https://n8n.innova1001.com.br/api/v1/workflows'); const response = await fetch('https://n8n.innova1001.com.br/api/v1/workflows', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-N8N-API-KEY': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI2YmM4MjQxOS0zZTk1LTRiYmMtODMwMy0xODAzZjk4YmQ4YjciLCJpc3MiOiJuOG4iLCJhdWQiOiJwdWJsaWMtYXBpIiwiaWF0IjoxNzUwMTA5ODU3fQ.cvqDVnD6ide9WCbtCx7bVDEvkPzJyO4EhGSDhY0xIjE' }, body: JSON.stringify(finalTemplate) }); console.log(`šŸ“” Status da requisição n8n: ${response.status}`); console.log('šŸ“‹ Headers da resposta:', Object.fromEntries(response.headers.entries())); if (!response.ok) { const errorText = await response.text(); console.error(`āŒ Erro ao criar workflow n8n: ${response.status} - ${errorText}`); throw new Error(`Failed to create workflow: ${response.status} - ${errorText}`); } const workflowData: N8nWorkflowResponse = await response.json(); console.log('āœ… Workflow criado com sucesso:', workflowData); // Extract workflow ID and webhook URL const workflowId = workflowData.id; // Try to get webhook URL from response, fallback to constructed URL let webhookUrl = ''; if (workflowData.nodes && workflowData.nodes[0] && workflowData.nodes[0].webhookUrls && workflowData.nodes[0].webhookUrls[0]) { webhookUrl = workflowData.nodes[0].webhookUrls[0]; } else { // Fallback: construct the webhook URL webhookUrl = `https://n8n.innova1001.com.br/webhook/${username}`; } console.log(`šŸ“Š Dados extraĆ­dos - ID: ${workflowId}, Webhook: ${webhookUrl}`); // Save the workflow info to the user's profile await saveWorkflowInfoToUser(userEmail, workflowId, webhookUrl); return { workflowId, webhookUrl }; } catch (error) { console.error('āŒ Erro na criação do workflow n8n:', error); // Log additional error details if (error instanceof Error) { console.error('āŒ Detalhes do erro:', { name: error.name, message: error.message, stack: error.stack }); } return null; } } /** * Saves workflow information to the user's profile * @param userEmail User's email * @param workflowId The n8n workflow ID * @param webhookUrl The webhook URL */ async function saveWorkflowInfoToUser( userEmail: string, workflowId: string, webhookUrl: string ): Promise { try { console.log(`šŸ’¾ Salvando informaƧƵes do workflow para: ${userEmail}`); console.log(`šŸ’¾ Dados a salvar - Workflow ID: ${workflowId}, Webhook URL: ${webhookUrl}`); // Update the user's profile with workflow information const { data, error } = await supabase .from('usuarios') .update({ webhook: webhookUrl, n8n_workflow_id: workflowId }) .eq('email', userEmail.trim().toLowerCase()) .select(); if (error) { console.error('āŒ Erro ao salvar info do workflow no usuĆ”rio:', error); throw error; } console.log(`āœ… InformaƧƵes do workflow salvas com sucesso:`, data); console.log(`āœ… Workflow ID: ${workflowId}, URL: ${webhookUrl}`); } catch (error) { console.error('āŒ Erro ao atualizar usuĆ”rio com info do workflow:', error); throw error; } }