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:
parent
a930b755eb
commit
176fe2c9f9
@ -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.",
|
||||
});
|
||||
|
||||
@ -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<void> {
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
Loading…
Reference in New Issue
Block a user