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.
This commit is contained in:
parent
f719a4cb1e
commit
0b9e6ee5df
@ -6,8 +6,7 @@ import { validateRegisterForm } from '@/utils/registerValidation';
|
|||||||
import RegisterFormFields from './RegisterFormFields';
|
import RegisterFormFields from './RegisterFormFields';
|
||||||
import { supabase } from '@/integrations/supabase/client';
|
import { supabase } from '@/integrations/supabase/client';
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
import { createN8nWorkflowForUser } from '@/services/n8nWorkflowCreationService';
|
import { sendNewUserWebhook } from '@/services/newUserWebhookService';
|
||||||
import { N8N_WORKFLOW_TEMPLATE } from '@/constants/n8nWorkflowTemplate';
|
|
||||||
|
|
||||||
interface RegisterFormProps {
|
interface RegisterFormProps {
|
||||||
isLoading: boolean;
|
isLoading: boolean;
|
||||||
@ -78,30 +77,30 @@ const RegisterForm = ({ isLoading, setIsLoading }: RegisterFormProps) => {
|
|||||||
duration: 10000,
|
duration: 10000,
|
||||||
});
|
});
|
||||||
|
|
||||||
// Create n8n workflow for the new user - CRITICAL STEP
|
// Send webhook to n8n workflow manager - NEW APPROACH
|
||||||
console.log('🔄 Iniciando criação de workflow n8n...');
|
console.log('📡 Enviando webhook para gerenciador n8n...');
|
||||||
console.log('📋 Email do usuário para workflow:', email);
|
console.log('📋 Email do usuário:', email);
|
||||||
console.log('📋 Template do workflow:', N8N_WORKFLOW_TEMPLATE);
|
console.log('📋 ID do usuário:', data.user.id);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const workflowResult = await createN8nWorkflowForUser(email, N8N_WORKFLOW_TEMPLATE);
|
const webhookSuccess = await sendNewUserWebhook(email, data.user.id);
|
||||||
if (workflowResult) {
|
if (webhookSuccess) {
|
||||||
console.log('✅ Workflow n8n criado com sucesso:', workflowResult);
|
console.log('✅ Webhook enviado com sucesso para n8n');
|
||||||
toast.success("Workflow configurado!", {
|
toast.success("Configuração automática iniciada!", {
|
||||||
description: `Seu workflow financeiro foi configurado automaticamente. ID: ${workflowResult.workflowId}`,
|
description: "Sua conta foi criada e a configuração automática do sistema foi iniciada.",
|
||||||
duration: 8000,
|
duration: 8000,
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
console.error('❌ Falha na criação do workflow n8n - resultado null');
|
console.error('❌ Falha no envio do webhook para n8n');
|
||||||
toast.error("Aviso: Workflow", {
|
toast.error("Aviso: Configuração", {
|
||||||
description: "Cadastro realizado, mas houve falha na configuração do workflow financeiro. Entre em contato com o suporte.",
|
description: "Cadastro realizado, mas houve falha na configuração automática. Entre em contato com o suporte.",
|
||||||
duration: 10000,
|
duration: 10000,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
} catch (workflowError) {
|
} catch (webhookError) {
|
||||||
console.error('❌ Erro crítico na criação do workflow n8n:', workflowError);
|
console.error('❌ Erro crítico no webhook para n8n:', webhookError);
|
||||||
toast.error("Aviso: Workflow", {
|
toast.error("Aviso: Configuração", {
|
||||||
description: "Cadastro realizado, mas houve falha na configuração do workflow financeiro. Entre em contato com o suporte.",
|
description: "Cadastro realizado, mas houve falha na configuração automática. Entre em contato com o suporte.",
|
||||||
duration: 10000,
|
duration: 10000,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
57
src/services/newUserWebhookService.ts
Normal file
57
src/services/newUserWebhookService.ts
Normal file
@ -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<boolean> {
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
Loading…
Reference in New Issue
Block a user