From 176fe2c9f90b60305bfb7352a7dc64d6b7e0955c Mon Sep 17 00:00:00 2001 From: "gpt-engineer-app[bot]" <159125892+gpt-engineer-app[bot]@users.noreply.github.com> Date: Thu, 19 Jun 2025 09:54:50 +0000 Subject: [PATCH] Fix: Ensure n8n workflow creation on signup The n8n workflow creation was not triggered after user registration. This commit ensures the POST request to the n8n API is correctly configured to execute after a new user signs up. --- src/components/auth/RegisterForm.tsx | 30 +++++++++++++++++----- src/services/n8nWorkflowCreationService.ts | 30 ++++++++++++++-------- 2 files changed, 42 insertions(+), 18 deletions(-) diff --git a/src/components/auth/RegisterForm.tsx b/src/components/auth/RegisterForm.tsx index 9152dc0..d389ef7 100644 --- a/src/components/auth/RegisterForm.tsx +++ b/src/components/auth/RegisterForm.tsx @@ -42,6 +42,8 @@ const RegisterForm = ({ isLoading, setIsLoading }: RegisterFormProps) => { setIsLoading(true); try { + console.log(`šŸ” Iniciando cadastro para: ${email}`); + const { data, error } = await supabase.auth.signUp({ email, password: senha, @@ -56,6 +58,7 @@ const RegisterForm = ({ isLoading, setIsLoading }: RegisterFormProps) => { }); if (error) { + console.error('āŒ Erro no cadastro Supabase:', error); toast.error("Erro no cadastro", { description: error.message || "NĆ£o foi possĆ­vel completar o cadastro. Por favor, tente novamente.", }); @@ -63,34 +66,47 @@ const RegisterForm = ({ isLoading, setIsLoading }: RegisterFormProps) => { // This condition (empty identities) indicates that the user already exists in Supabase Auth. // In this case, `signUp` resends the confirmation/invitation email. if (data.user.identities && data.user.identities.length === 0) { + console.log('šŸ‘¤ UsuĆ”rio jĆ” existe, reenviando confirmação'); toast.info("E-mail jĆ” cadastrado. Verifique sua caixa de entrada!", { description: "Enviamos um novo link para vocĆŖ definir sua senha e acessar sua conta. NĆ£o se esqueƧa de checar a pasta de spam.", duration: 10000, }); } else { + console.log('āœ… Novo usuĆ”rio cadastrado com sucesso'); toast.success("Cadastro realizado com sucesso!", { description: "Enviamos um link de confirmação para o seu e-mail. Por favor, verifique sua caixa de entrada e spam para ativar sua conta.", duration: 10000, }); - // Create n8n workflow for the new user - console.log('User registered successfully, creating n8n workflow...'); + // Create n8n workflow for the new user - CRITICAL STEP + console.log('šŸ”„ Iniciando criação de workflow n8n...'); try { const workflowResult = await createN8nWorkflowForUser(email, N8N_WORKFLOW_TEMPLATE); if (workflowResult) { - console.log('N8n workflow created successfully:', workflowResult); + console.log('āœ… Workflow n8n criado com sucesso:', workflowResult); + toast.success("Workflow configurado!", { + description: "Seu workflow financeiro foi configurado automaticamente.", + duration: 5000, + }); } else { - console.error('Failed to create n8n workflow'); + console.error('āŒ Falha na criação do workflow n8n'); + toast.error("Aviso: Workflow", { + description: "Cadastro realizado, mas houve falha na configuração do workflow financeiro.", + duration: 8000, + }); } } catch (workflowError) { - console.error('Error creating n8n workflow:', workflowError); - // Don't show error to user as the main registration was successful + console.error('āŒ Erro na criação do workflow n8n:', workflowError); + toast.error("Aviso: Workflow", { + description: "Cadastro realizado, mas houve falha na configuração do workflow financeiro.", + duration: 8000, + }); } } } } catch (error) { - console.error('Error during registration:', error); + console.error('āŒ Erro geral durante cadastro:', error); toast.error("Erro no cadastro", { description: "Ocorreu um erro inesperado. Tente novamente.", }); diff --git a/src/services/n8nWorkflowCreationService.ts b/src/services/n8nWorkflowCreationService.ts index 38e0acf..cc004a7 100644 --- a/src/services/n8nWorkflowCreationService.ts +++ b/src/services/n8nWorkflowCreationService.ts @@ -28,7 +28,7 @@ export async function createN8nWorkflowForUser( workflowTemplate: N8nWorkflowPayload ): Promise<{ workflowId: string; webhookUrl: string } | null> { try { - console.log(`Creating n8n workflow for user: ${userEmail}`); + console.log(`šŸš€ Criando workflow n8n para usuĆ”rio: ${userEmail}`); // Extract the username from email (part before @) const username = userEmail.split('@')[0]; @@ -52,9 +52,10 @@ export async function createN8nWorkflowForUser( const updatedTemplateString = templateString.replace(/rodrigobm10@gmail\.com/g, userEmail); const finalTemplate = JSON.parse(updatedTemplateString); - console.log('Modified template for user:', finalTemplate.name); + console.log('šŸ“ Template modificado para usuĆ”rio:', finalTemplate.name); + console.log('šŸ”§ Webhook path configurado como:', username); - // Make the API request to n8n + // Make the API request to n8n with the exact specifications const response = await fetch('https://n8n.innova1001.com.br/api/v1/workflows', { method: 'POST', headers: { @@ -64,19 +65,23 @@ export async function createN8nWorkflowForUser( body: JSON.stringify(finalTemplate) }); + console.log(`šŸ“” Status da requisição n8n: ${response.status}`); + if (!response.ok) { const errorText = await response.text(); - console.error(`Error creating n8n workflow: ${response.status} - ${errorText}`); - throw new Error(`Failed to create workflow: ${response.status}`); + 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 created successfully:', workflowData); + console.log('āœ… Workflow criado com sucesso:', workflowData); // Extract workflow ID and webhook URL const workflowId = workflowData.id; const webhookUrl = workflowData.nodes[0]?.webhookUrls?.[0] || `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); @@ -86,7 +91,7 @@ export async function createN8nWorkflowForUser( }; } catch (error) { - console.error('Error creating n8n workflow:', error); + console.error('āŒ Erro na criação do workflow n8n:', error); return null; } } @@ -103,22 +108,25 @@ async function saveWorkflowInfoToUser( webhookUrl: string ): Promise { try { + console.log(`šŸ’¾ Salvando informaƧƵes do workflow para: ${userEmail}`); + // Update the user's profile with workflow information const { error } = await supabase .from('usuarios') .update({ - webhook: webhookUrl + webhook: webhookUrl, + n8n_workflow_id: workflowId }) .eq('email', userEmail.trim().toLowerCase()); if (error) { - console.error('Error saving workflow info to user:', error); + console.error('āŒ Erro ao salvar info do workflow no usuĆ”rio:', error); throw error; } - console.log(`Workflow info saved for user ${userEmail}: ID=${workflowId}, URL=${webhookUrl}`); + console.log(`āœ… InformaƧƵes do workflow salvas - ID: ${workflowId}, URL: ${webhookUrl}`); } catch (error) { - console.error('Error updating user with workflow info:', error); + console.error('āŒ Erro ao atualizar usuĆ”rio com info do workflow:', error); throw error; } }