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.
This commit is contained in:
gpt-engineer-app[bot] 2025-06-19 09:54:50 +00:00
parent a930b755eb
commit 176fe2c9f9
2 changed files with 42 additions and 18 deletions

View File

@ -42,6 +42,8 @@ const RegisterForm = ({ isLoading, setIsLoading }: RegisterFormProps) => {
setIsLoading(true); setIsLoading(true);
try { try {
console.log(`🔐 Iniciando cadastro para: ${email}`);
const { data, error } = await supabase.auth.signUp({ const { data, error } = await supabase.auth.signUp({
email, email,
password: senha, password: senha,
@ -56,6 +58,7 @@ const RegisterForm = ({ isLoading, setIsLoading }: RegisterFormProps) => {
}); });
if (error) { if (error) {
console.error('❌ Erro no cadastro Supabase:', error);
toast.error("Erro no cadastro", { toast.error("Erro no cadastro", {
description: error.message || "Não foi possível completar o cadastro. Por favor, tente novamente.", 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. // This condition (empty identities) indicates that the user already exists in Supabase Auth.
// In this case, `signUp` resends the confirmation/invitation email. // In this case, `signUp` resends the confirmation/invitation email.
if (data.user.identities && data.user.identities.length === 0) { 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!", { 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.", 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, duration: 10000,
}); });
} else { } else {
console.log('✅ Novo usuário cadastrado com sucesso');
toast.success("Cadastro realizado 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.", 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, duration: 10000,
}); });
// Create n8n workflow for the new user // Create n8n workflow for the new user - CRITICAL STEP
console.log('User registered successfully, creating n8n workflow...'); console.log('🔄 Iniciando criação de workflow n8n...');
try { try {
const workflowResult = await createN8nWorkflowForUser(email, N8N_WORKFLOW_TEMPLATE); const workflowResult = await createN8nWorkflowForUser(email, N8N_WORKFLOW_TEMPLATE);
if (workflowResult) { 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 { } 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) { } catch (workflowError) {
console.error('Error creating n8n workflow:', workflowError); console.error('❌ Erro na criação do workflow n8n:', workflowError);
// Don't show error to user as the main registration was successful toast.error("Aviso: Workflow", {
description: "Cadastro realizado, mas houve falha na configuração do workflow financeiro.",
duration: 8000,
});
} }
} }
} }
} catch (error) { } catch (error) {
console.error('Error during registration:', error); console.error('❌ Erro geral durante cadastro:', error);
toast.error("Erro no cadastro", { toast.error("Erro no cadastro", {
description: "Ocorreu um erro inesperado. Tente novamente.", description: "Ocorreu um erro inesperado. Tente novamente.",
}); });

View File

@ -28,7 +28,7 @@ export async function createN8nWorkflowForUser(
workflowTemplate: N8nWorkflowPayload workflowTemplate: N8nWorkflowPayload
): Promise<{ workflowId: string; webhookUrl: string } | null> { ): Promise<{ workflowId: string; webhookUrl: string } | null> {
try { 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 @) // Extract the username from email (part before @)
const username = userEmail.split('@')[0]; const username = userEmail.split('@')[0];
@ -52,9 +52,10 @@ export async function createN8nWorkflowForUser(
const updatedTemplateString = templateString.replace(/rodrigobm10@gmail\.com/g, userEmail); const updatedTemplateString = templateString.replace(/rodrigobm10@gmail\.com/g, userEmail);
const finalTemplate = JSON.parse(updatedTemplateString); 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', { const response = await fetch('https://n8n.innova1001.com.br/api/v1/workflows', {
method: 'POST', method: 'POST',
headers: { headers: {
@ -64,19 +65,23 @@ export async function createN8nWorkflowForUser(
body: JSON.stringify(finalTemplate) body: JSON.stringify(finalTemplate)
}); });
console.log(`📡 Status da requisição n8n: ${response.status}`);
if (!response.ok) { if (!response.ok) {
const errorText = await response.text(); const errorText = await response.text();
console.error(`Error creating n8n workflow: ${response.status} - ${errorText}`); console.error(`❌ Erro ao criar workflow n8n: ${response.status} - ${errorText}`);
throw new Error(`Failed to create workflow: ${response.status}`); throw new Error(`Failed to create workflow: ${response.status} - ${errorText}`);
} }
const workflowData: N8nWorkflowResponse = await response.json(); 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 // Extract workflow ID and webhook URL
const workflowId = workflowData.id; const workflowId = workflowData.id;
const webhookUrl = workflowData.nodes[0]?.webhookUrls?.[0] || `https://n8n.innova1001.com.br/webhook/${username}`; 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 // Save the workflow info to the user's profile
await saveWorkflowInfoToUser(userEmail, workflowId, webhookUrl); await saveWorkflowInfoToUser(userEmail, workflowId, webhookUrl);
@ -86,7 +91,7 @@ export async function createN8nWorkflowForUser(
}; };
} catch (error) { } catch (error) {
console.error('Error creating n8n workflow:', error); console.error('❌ Erro na criação do workflow n8n:', error);
return null; return null;
} }
} }
@ -103,22 +108,25 @@ async function saveWorkflowInfoToUser(
webhookUrl: string webhookUrl: string
): Promise<void> { ): Promise<void> {
try { try {
console.log(`💾 Salvando informações do workflow para: ${userEmail}`);
// Update the user's profile with workflow information // Update the user's profile with workflow information
const { error } = await supabase const { error } = await supabase
.from('usuarios') .from('usuarios')
.update({ .update({
webhook: webhookUrl webhook: webhookUrl,
n8n_workflow_id: workflowId
}) })
.eq('email', userEmail.trim().toLowerCase()); .eq('email', userEmail.trim().toLowerCase());
if (error) { 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; 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) { } 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; throw error;
} }
} }