diff --git a/src/services/n8nWorkflowService.ts b/src/services/n8nWorkflowService.ts index 8676c46..61a2551 100644 --- a/src/services/n8nWorkflowService.ts +++ b/src/services/n8nWorkflowService.ts @@ -37,20 +37,35 @@ export async function createWorkflowInN8n(email: string): Promise<{ id: string } return { id: grupo.workflow_id }; } - // Get the URL from an environment variable or build it - const supabaseUrl = import.meta.env.VITE_SUPABASE_URL || "https://tnurlgbvfsxwqgwxamni.supabase.co"; + // Instead of using the Edge Function, we'll use a direct API call to n8n + // The API endpoint for the n8n workflow creation + const n8nApiUrl = 'https://n8n.innova1001.com.br/api/v1/workflows'; + const apiKey = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI2YmM4MjQxOS0zZTk1LTRiYmMtODMwMy0xODAzZjk4YmQ4YjciLCJpc3MiOiJuOG4iLCJhdWQiOiJwdWJsaWMtYXBpIiwiaWF0IjoxNzQ3NzM0NzYyLCJleHAiOjE3NTAzMDIwMDB9.Evr_o42xLJPq1c2p5SUWo00IY85WXp8s_nqSy64V-is'; - // Call our edge function to create the workflow + // Create the workflow data + const workflowData = { + name: `Workflow Home Finance - ${email}`, + nodes: [], + connections: {}, + settings: {} + }; + + // Use the Edge Function as a proxy to make the n8n API call + // This avoids CORS issues since the call is made server-side + const supabaseUrl = import.meta.env.VITE_SUPABASE_URL || 'https://tnurlgbvfsxwqgwxamni.supabase.co'; + + console.log('Calling Edge Function to create workflow in n8n'); const response = await fetch(`${supabaseUrl}/functions/v1/create-n8n-workflow`, { method: 'POST', headers: { 'Content-Type': 'application/json', - // Use getSession() to get the current session 'Authorization': `Bearer ${(await supabase.auth.getSession()).data.session?.access_token || ''}` }, body: JSON.stringify({ email: email, - grupoId: grupo.id + grupoId: grupo.id, + apiKey: apiKey, // Pass the API key to the Edge Function + workflowData: workflowData // Pass the workflow data }) }); @@ -72,6 +87,19 @@ export async function createWorkflowInN8n(email: string): Promise<{ id: string } const data = await response.json(); console.log('Resposta da criação de workflow:', data); + // After successful workflow creation, update the group record with the workflow ID + if (data.workflow_id) { + const { error: updateError } = await supabase + .from('grupos_whatsapp') + .update({ workflow_id: data.workflow_id }) + .eq('id', grupo.id); + + if (updateError) { + console.error('Erro ao atualizar workflow_id no grupo:', updateError); + // We still return the workflow ID even if there was an error updating the group + } + } + return { id: data.workflow_id }; } catch (error) { console.error('Erro na requisição de criação de workflow:', error); diff --git a/supabase/functions/create-n8n-workflow/index.ts b/supabase/functions/create-n8n-workflow/index.ts index fa6bd65..d948b99 100644 --- a/supabase/functions/create-n8n-workflow/index.ts +++ b/supabase/functions/create-n8n-workflow/index.ts @@ -1,120 +1,129 @@ -import { serve } from "https://deno.land/std@0.168.0/http/server.ts"; -import { createClient } from "https://esm.sh/@supabase/supabase-js@2"; +import { serve } from 'https://deno.land/std@0.177.0/http/server.ts' +import { createClient } from 'https://esm.sh/@supabase/supabase-js@2.20.0' -const N8N_API_URL = 'https://n8n.innova1001.com.br/api/v1/workflows'; -const N8N_API_KEY = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI2YmM4MjQxOS0zZTk1LTRiYmMtODMwMy0xODAzZjk4YmQ4YjciLCJpc3MiOiJuOG4iLCJhdWQiOiJwdWJsaWMtYXBpIiwiaWF0IjoxNzQ3NzM0NzYyLCJleHAiOjE3NTAzMDIwMDB9.Evr_o42xLJPq1c2p5SUWo00IY85WXp8s_nqSy64V-is'; +interface RequestBody { + email: string + grupoId: number + apiKey: string + workflowData: { + name: string + nodes: any[] + connections: any + settings: any + } +} serve(async (req) => { - // CORS headers - const headers = { - "Access-Control-Allow-Origin": "*", - "Access-Control-Allow-Headers": "authorization, x-client-info, apikey, content-type", - "Content-Type": "application/json", - }; - - // Handle preflight requests - if (req.method === 'OPTIONS') { - return new Response(null, { headers, status: 204 }); - } - try { - // Parse the request body - const requestData = await req.json(); - const { email, grupoId } = requestData; - - if (!email) { - return new Response( - JSON.stringify({ error: 'Email é obrigatório' }), - { status: 400, headers } - ); + // Handle CORS preflight request + if (req.method === 'OPTIONS') { + return new Response(null, { + status: 204, + headers: { + 'Access-Control-Allow-Origin': '*', + 'Access-Control-Allow-Methods': 'POST, OPTIONS', + 'Access-Control-Allow-Headers': 'Content-Type, Authorization', + }, + }) } - if (!grupoId) { - return new Response( - JSON.stringify({ error: 'ID do grupo é obrigatório' }), - { status: 400, headers } - ); - } - - console.log(`Creating workflow for email: ${email}, group ID: ${grupoId}`); + // Extract request body + const { email, grupoId, apiKey, workflowData }: RequestBody = await req.json() - // Create Supabase client - const supabaseUrl = Deno.env.get('SUPABASE_URL') ?? ''; - const supabaseAnonKey = Deno.env.get('SUPABASE_ANON_KEY') ?? ''; - const supabase = createClient(supabaseUrl, supabaseAnonKey); + if (!email || !grupoId || !apiKey) { + return new Response( + JSON.stringify({ error: 'Email, grupo ID e chave API são obrigatórios' }), + { + status: 400, + headers: { + 'Content-Type': 'application/json', + 'Access-Control-Allow-Origin': '*', + } + } + ) + } - // Create workflow in n8n - const n8nResponse = await fetch(N8N_API_URL, { + console.log(`Creating workflow for email: ${email}, group: ${grupoId}`) + + // Make request to n8n API + const n8nResponse = await fetch('https://n8n.innova1001.com.br/api/v1/workflows', { method: 'POST', headers: { - 'X-N8N-API-KEY': N8N_API_KEY, - 'Content-Type': 'application/json' + 'Content-Type': 'application/json', + 'X-N8N-API-KEY': apiKey, }, - body: JSON.stringify({ - name: `Workflow Home Finance - ${email}`, - nodes: [], - connections: {}, - settings: {} - }) - }); - - console.log(`N8N API response status: ${n8nResponse.status}`); + body: JSON.stringify(workflowData), + }) if (!n8nResponse.ok) { - const errorText = await n8nResponse.text(); - console.error(`N8N API error: ${errorText}`); - + const errorText = await n8nResponse.text() + console.error(`n8n API error: ${n8nResponse.status} - ${errorText}`) return new Response( JSON.stringify({ - error: 'Erro ao criar workflow no n8n', - details: errorText, - status: n8nResponse.status + error: 'Error calling n8n API', + status: n8nResponse.status, + details: errorText }), - { status: 500, headers } - ); + { + status: n8nResponse.status, + headers: { + 'Content-Type': 'application/json', + 'Access-Control-Allow-Origin': '*', + } + } + ) } - const workflowData = await n8nResponse.json(); - console.log(`Workflow created successfully with ID: ${workflowData.id}`); - - // Update the workflow_id in grupos_whatsapp table - const { data: updateData, error: updateError } = await supabase - .from('grupos_whatsapp') - .update({ workflow_id: workflowData.id }) - .eq('id', grupoId) - .select(); - - if (updateError) { - console.error(`Error updating grupo_whatsapp: ${JSON.stringify(updateError)}`); + const workflowResponse = await n8nResponse.json() + + // Extract workflow ID from response + const workflowId = workflowResponse.id + + if (!workflowId) { + console.error('No workflow ID in n8n response', workflowResponse) return new Response( - JSON.stringify({ - error: 'Erro ao atualizar o grupo com o workflow ID', - details: updateError - }), - { status: 500, headers } - ); + JSON.stringify({ error: 'No workflow ID in response', details: workflowResponse }), + { + status: 500, + headers: { + 'Content-Type': 'application/json', + 'Access-Control-Allow-Origin': '*', + } + } + ) } + + console.log(`Workflow created with ID: ${workflowId}`) - console.log(`Group ${grupoId} updated with workflow ID ${workflowData.id}`); - - // Return success response + // Success response return new Response( JSON.stringify({ success: true, - workflow_id: workflowData.id, - message: 'Workflow criado e associado ao grupo com sucesso' + workflow_id: workflowId, + message: 'Workflow created successfully', + details: workflowResponse }), - { headers } - ); + { + status: 200, + headers: { + 'Content-Type': 'application/json', + 'Access-Control-Allow-Origin': '*', + } + } + ) } catch (error) { - console.error(`Unexpected error: ${error.message}`); + console.error('Error in Edge Function:', error) + return new Response( - JSON.stringify({ - error: 'Erro interno do servidor', - details: error.message - }), - { status: 500, headers } - ); + JSON.stringify({ error: 'Internal server error', details: error.message }), + { + status: 500, + headers: { + 'Content-Type': 'application/json', + 'Access-Control-Allow-Origin': '*', + } + } + ) } -}); +})