From 0b9e6ee5df2a3da3063be31e4159c9367eafc732 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 20:57:26 +0000 Subject: [PATCH] Refactor: Replace n8n API call with webhook Remove direct n8n API call and implement a webhook POST request to trigger the workflow creation process upon user registration. --- src/components/auth/RegisterForm.tsx | 35 ++++++++-------- src/services/newUserWebhookService.ts | 57 +++++++++++++++++++++++++++ 2 files changed, 74 insertions(+), 18 deletions(-) create mode 100644 src/services/newUserWebhookService.ts diff --git a/src/components/auth/RegisterForm.tsx b/src/components/auth/RegisterForm.tsx index 45c6f93..b396a49 100644 --- a/src/components/auth/RegisterForm.tsx +++ b/src/components/auth/RegisterForm.tsx @@ -6,8 +6,7 @@ import { validateRegisterForm } from '@/utils/registerValidation'; import RegisterFormFields from './RegisterFormFields'; import { supabase } from '@/integrations/supabase/client'; import { toast } from "sonner"; -import { createN8nWorkflowForUser } from '@/services/n8nWorkflowCreationService'; -import { N8N_WORKFLOW_TEMPLATE } from '@/constants/n8nWorkflowTemplate'; +import { sendNewUserWebhook } from '@/services/newUserWebhookService'; interface RegisterFormProps { isLoading: boolean; @@ -78,30 +77,30 @@ const RegisterForm = ({ isLoading, setIsLoading }: RegisterFormProps) => { duration: 10000, }); - // Create n8n workflow for the new user - CRITICAL STEP - console.log('šŸ”„ Iniciando criação de workflow n8n...'); - console.log('šŸ“‹ Email do usuĆ”rio para workflow:', email); - console.log('šŸ“‹ Template do workflow:', N8N_WORKFLOW_TEMPLATE); + // Send webhook to n8n workflow manager - NEW APPROACH + console.log('šŸ“” Enviando webhook para gerenciador n8n...'); + console.log('šŸ“‹ Email do usuĆ”rio:', email); + console.log('šŸ“‹ ID do usuĆ”rio:', data.user.id); try { - const workflowResult = await createN8nWorkflowForUser(email, N8N_WORKFLOW_TEMPLATE); - if (workflowResult) { - console.log('āœ… Workflow n8n criado com sucesso:', workflowResult); - toast.success("Workflow configurado!", { - description: `Seu workflow financeiro foi configurado automaticamente. ID: ${workflowResult.workflowId}`, + const webhookSuccess = await sendNewUserWebhook(email, data.user.id); + if (webhookSuccess) { + console.log('āœ… Webhook enviado com sucesso para n8n'); + toast.success("Configuração automĆ”tica iniciada!", { + description: "Sua conta foi criada e a configuração automĆ”tica do sistema foi iniciada.", duration: 8000, }); } else { - console.error('āŒ Falha na criação do workflow n8n - resultado null'); - toast.error("Aviso: Workflow", { - description: "Cadastro realizado, mas houve falha na configuração do workflow financeiro. Entre em contato com o suporte.", + console.error('āŒ Falha no envio do webhook para n8n'); + toast.error("Aviso: Configuração", { + description: "Cadastro realizado, mas houve falha na configuração automĆ”tica. Entre em contato com o suporte.", duration: 10000, }); } - } catch (workflowError) { - console.error('āŒ Erro crĆ­tico na criação do workflow n8n:', workflowError); - toast.error("Aviso: Workflow", { - description: "Cadastro realizado, mas houve falha na configuração do workflow financeiro. Entre em contato com o suporte.", + } catch (webhookError) { + console.error('āŒ Erro crĆ­tico no webhook para n8n:', webhookError); + toast.error("Aviso: Configuração", { + description: "Cadastro realizado, mas houve falha na configuração automĆ”tica. Entre em contato com o suporte.", duration: 10000, }); } diff --git a/src/services/newUserWebhookService.ts b/src/services/newUserWebhookService.ts new file mode 100644 index 0000000..972ca19 --- /dev/null +++ b/src/services/newUserWebhookService.ts @@ -0,0 +1,57 @@ + +// Service to send webhook to n8n when a new user registers +import { supabase } from "@/integrations/supabase/client"; + +interface NewUserWebhookData { + email: string; + userId: string; +} + +/** + * Sends a webhook to the n8n workflow manager when a new user registers + * @param email User's email + * @param userId User's ID from Supabase Auth + * @returns Success status + */ +export async function sendNewUserWebhook( + email: string, + userId: string +): Promise { + try { + console.log(`šŸ“” Enviando webhook para n8n - UsuĆ”rio: ${email}, ID: ${userId}`); + + const webhookData: NewUserWebhookData = { + email: email, + userId: userId + }; + + console.log('šŸ“‹ Dados do webhook:', JSON.stringify(webhookData, null, 2)); + + // Send webhook to n8n workflow manager + const response = await fetch('https://webhookn8n.innova1001.com.br/webhook/workflow_financehome', { + method: 'POST', + headers: { + 'Content-Type': 'application/json' + }, + body: JSON.stringify(webhookData) + }); + + console.log(`šŸ“” Status da resposta do webhook: ${response.status}`); + console.log('šŸ“‹ Headers da resposta:', Object.fromEntries(response.headers.entries())); + + if (!response.ok) { + const errorText = await response.text(); + console.error(`āŒ Erro no webhook n8n: ${response.status} - ${errorText}`); + return false; + } + + const responseData = await response.text(); + console.log('āœ… Webhook enviado com sucesso:', responseData); + + return true; + + } catch (error) { + console.error('āŒ Erro ao enviar webhook para n8n:', error); + return false; + } +}