Add workflow integration for WhatsApp groups

Integrate n8n workflow cloning upon WhatsApp group registration.  Adds a `workflow_id` column to the `grupos_whatsapp` table and updates the `cadastrarGrupoWhatsApp` function to call the n8n webhook, capturing the returned workflow ID and saving it to the database.  The button "Cadastrar Grupo" is only visible when the user is logged in.
This commit is contained in:
gpt-engineer-app[bot] 2025-05-20 02:24:58 +00:00
parent 9331f37ec5
commit 4f84ab9a9f
4 changed files with 93 additions and 2 deletions

View File

@ -129,6 +129,7 @@ export type Database = {
remote_jid: string
status: string | null
user_id: string
workflow_id: string | null
}
Insert: {
created_at?: string | null
@ -138,6 +139,7 @@ export type Database = {
remote_jid: string
status?: string | null
user_id: string
workflow_id?: string | null
}
Update: {
created_at?: string | null
@ -147,6 +149,7 @@ export type Database = {
remote_jid?: string
status?: string | null
user_id?: string
workflow_id?: string | null
}
Relationships: []
}

View File

@ -47,6 +47,15 @@ const GruposWhatsApp = () => {
// Cadastrar novo grupo
const handleCadastrarGrupo = async () => {
if (!userEmail) {
toast({
title: 'Erro',
description: 'Você precisa estar logado para cadastrar um grupo',
variant: 'destructive',
});
return;
}
setCadastrando(true);
try {
const novoGrupo = await cadastrarGrupoWhatsApp();
@ -96,7 +105,7 @@ const GruposWhatsApp = () => {
</Button>
<Button
onClick={handleCadastrarGrupo}
disabled={cadastrando}
disabled={cadastrando || !userEmail}
>
{cadastrando ? (
<>
@ -156,6 +165,7 @@ const GruposWhatsApp = () => {
<TableHead>ID</TableHead>
<TableHead>Nome do grupo</TableHead>
<TableHead>Status</TableHead>
<TableHead>Workflow</TableHead>
<TableHead>Cadastro</TableHead>
</TableRow>
</TableHeader>
@ -175,6 +185,17 @@ const GruposWhatsApp = () => {
{grupo.remote_jid ? 'Ativo' : 'Pendente'}
</Badge>
</TableCell>
<TableCell>
{grupo.workflow_id ? (
<Badge variant="secondary" className="bg-green-100 text-green-800">
Configurado
</Badge>
) : (
<Badge variant="outline" className="text-gray-500">
Não configurado
</Badge>
)}
</TableCell>
<TableCell>{new Date(grupo.created_at).toLocaleDateString()}</TableCell>
</TableRow>
))}
@ -188,7 +209,7 @@ const GruposWhatsApp = () => {
variant="outline"
className="mt-4"
onClick={handleCadastrarGrupo}
disabled={cadastrando}
disabled={cadastrando || !userEmail}
>
<Plus className="h-4 w-4 mr-2" />
Cadastrar seu primeiro grupo

View File

@ -32,6 +32,22 @@ export async function cadastrarGrupoWhatsApp(): Promise<WhatsAppGroup | null> {
}
console.log('Grupo WhatsApp cadastrado com sucesso:', data);
// Tentativa de clonagem do workflow do n8n
try {
const grupoId = data[0].remote_jid;
const result = await cloneN8nWorkflow(normalizedEmail, grupoId);
if (result && result.workflow_id) {
await atualizarWorkflowId(data[0].id, result.workflow_id);
// Atualizar o objeto data com o workflow_id
data[0].workflow_id = result.workflow_id;
}
} catch (n8nError) {
console.error('Erro ao clonar workflow do n8n:', n8nError);
// Não impede a criação do grupo, apenas não adiciona o workflow_id
}
return data[0];
} catch (error) {
console.error('Erro ao cadastrar grupo do WhatsApp:', error);
@ -71,3 +87,53 @@ export async function listarGruposWhatsApp(): Promise<WhatsAppGroup[]> {
return [];
}
}
// Função para clonar o workflow do n8n
async function cloneN8nWorkflow(email: string, grupoId: string): Promise<{ workflow_id: string } | null> {
try {
console.log(`Clonando workflow para email: ${email}, grupoId: ${grupoId}`);
const response = await fetch('https://n8n.innova1001.com.br/webhook/clone-workflow', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: email,
grupo_id: grupoId
})
});
if (!response.ok) {
throw new Error(`Erro ao clonar workflow: ${response.statusText}`);
}
const data = await response.json();
console.log('Resposta da clonagem de workflow:', data);
return data;
} catch (error) {
console.error('Erro na requisição de clonagem de workflow:', error);
return null;
}
}
// Função para atualizar o workflow_id no banco de dados
async function atualizarWorkflowId(groupId: number, workflowId: string): Promise<void> {
try {
const { error } = await supabase
.from('grupos_whatsapp')
.update({ workflow_id: workflowId })
.eq('id', groupId);
if (error) {
console.error('Erro ao atualizar workflow_id:', error);
throw error;
}
console.log(`Workflow ID ${workflowId} atualizado com sucesso para o grupo ${groupId}`);
} catch (error) {
console.error('Erro ao atualizar workflow_id no banco de dados:', error);
throw error;
}
}

View File

@ -66,4 +66,5 @@ export interface WhatsAppGroup {
created_at: string;
status: string;
login: string; // E-mail do usuário como identificador principal
workflow_id?: string | null; // ID do workflow no n8n
}