diff --git a/src/components/whatsappGroups/CreateGroupForm.tsx b/src/components/whatsappGroups/CreateGroupForm.tsx index 642d4a3..281ae49 100644 --- a/src/components/whatsappGroups/CreateGroupForm.tsx +++ b/src/components/whatsappGroups/CreateGroupForm.tsx @@ -1,10 +1,14 @@ -import { useExistingInstanceCheck } from '@/hooks/whatsapp/useExistingInstanceCheck'; // <--- Hook UNIFICADO! +import { useEffect, useState } from 'react'; +import { useExistingInstanceCheck } from '@/hooks/whatsapp/useExistingInstanceCheck'; import { useGroupCreation } from '@/hooks/whatsappGroups/useGroupCreation'; +import { listarGruposWhatsApp } from '@/services/gruposWhatsAppService'; import LoadingState from './LoadingState'; import NoInstanceState from './NoInstanceState'; import GroupCreationForm from './GroupCreationForm'; -import { useEffect } from 'react'; +import { Alert, AlertDescription } from '@/components/ui/alert'; +import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card'; +import { Info, Loader2 } from 'lucide-react'; interface CreateGroupFormProps { userEmail: string; @@ -12,7 +16,10 @@ interface CreateGroupFormProps { } const CreateGroupForm = ({ userEmail, onSuccess }: CreateGroupFormProps) => { - // Use o hook UNIFICADO E CORRETO + const [verificandoGrupos, setVerificandoGrupos] = useState(true); + const [jaTemGrupo, setJaTemGrupo] = useState(false); + const [grupoExistente, setGrupoExistente] = useState(null); + const { hasExistingInstance, checkingExistingInstance, @@ -22,18 +29,74 @@ const CreateGroupForm = ({ userEmail, onSuccess }: CreateGroupFormProps) => { const { cadastrando, handleCadastrarGrupo } = useGroupCreation(userEmail, onSuccess); + // Verificar se o usuário já tem grupos cadastrados + const verificarGruposExistentes = async () => { + if (!userEmail) return; + + setVerificandoGrupos(true); + try { + console.log('🔍 Verificando grupos existentes para:', userEmail); + const grupos = await listarGruposWhatsApp(); + + if (grupos && grupos.length > 0) { + console.log('✅ Usuário já possui grupos:', grupos); + setJaTemGrupo(true); + setGrupoExistente(grupos[0]); // Pegar o primeiro grupo + } else { + console.log('📝 Usuário não possui grupos, pode cadastrar'); + setJaTemGrupo(false); + setGrupoExistente(null); + } + } catch (error) { + console.error('❌ Erro ao verificar grupos existentes:', error); + setJaTemGrupo(false); + } finally { + setVerificandoGrupos(false); + } + }; + useEffect(() => { recheckInstance(); - }, [userEmail]); // Re-verifica quando o email muda + verificarGruposExistentes(); + }, [userEmail]); - if (checkingExistingInstance) { - return ; + if (checkingExistingInstance || verificandoGrupos) { + return ; } - // A lógica agora é a mesma da outra página: `hasExistingInstance` - //if (!hasExistingInstance) { - // return ; - //} + // Se já tem grupo, mostrar informação + if (jaTemGrupo && grupoExistente) { + return ( + + + Cadastrar novo grupo + + Você já possui um grupo cadastrado + + + + + + + Grupo já cadastrado: {grupoExistente.nome_grupo || 'Grupo sem nome'} +
+ + Status: {grupoExistente.status || 'pendente'} + {grupoExistente.remote_jid && grupoExistente.remote_jid !== '' && ( + • ID: {grupoExistente.remote_jid} + )} + +
+
+
+
+ ); + } + + // Se não tem instância conectada, mostrar estado de sem instância + if (!hasExistingInstance) { + return ; + } const handleSubmit = (nomeGrupo: string) => { handleCadastrarGrupo(nomeGrupo, existingInstanceData); diff --git a/src/components/whatsappGroups/CreateGroupFormSimple.tsx b/src/components/whatsappGroups/CreateGroupFormSimple.tsx index 6582fa0..b4dd4f6 100644 --- a/src/components/whatsappGroups/CreateGroupFormSimple.tsx +++ b/src/components/whatsappGroups/CreateGroupFormSimple.tsx @@ -1,13 +1,13 @@ -import { useState } from 'react'; +import { useState, useEffect } from 'react'; import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import { Label } from '@/components/ui/label'; import { Alert, AlertDescription } from '@/components/ui/alert'; -import { Loader2, AlertCircle, CheckCircle2 } from 'lucide-react'; +import { Loader2, AlertCircle, CheckCircle2, Info } from 'lucide-react'; import { useToast } from '@/hooks/use-toast'; -import { verificarInstanciaWhatsApp } from '@/services/gruposWhatsAppService'; +import { verificarInstanciaWhatsApp, listarGruposWhatsApp } from '@/services/gruposWhatsAppService'; import { findOrCreateWhatsAppGroup } from '@/services/whatsAppGroupsService'; import { createWorkflowInN8n } from '@/services/n8nWorkflowService'; import { createEvolutionWebhook } from '@/services/whatsApp/webhookService'; @@ -22,6 +22,9 @@ const CreateGroupFormSimple = ({ userEmail, onSuccess }: CreateGroupFormProps) = const { toast } = useToast(); const [nomeGrupo, setNomeGrupo] = useState(''); const [carregando, setCarregando] = useState(false); + const [verificandoGrupos, setVerificandoGrupos] = useState(true); + const [jaTemGrupo, setJaTemGrupo] = useState(false); + const [grupoExistente, setGrupoExistente] = useState(null); const [webhookEnviado, setWebhookEnviado] = useState(false); const [workflowAtivado, setWorkflowAtivado] = useState(false); const [mensagemStatus, setMensagemStatus] = useState<{ @@ -29,9 +32,48 @@ const CreateGroupFormSimple = ({ userEmail, onSuccess }: CreateGroupFormProps) = texto: string; } | null>(null); + // Verificar se o usuário já tem grupos cadastrados + const verificarGruposExistentes = async () => { + if (!userEmail) return; + + setVerificandoGrupos(true); + try { + console.log('🔍 Verificando grupos existentes para:', userEmail); + const grupos = await listarGruposWhatsApp(); + + if (grupos && grupos.length > 0) { + console.log('✅ Usuário já possui grupos:', grupos); + setJaTemGrupo(true); + setGrupoExistente(grupos[0]); // Pegar o primeiro grupo + } else { + console.log('📝 Usuário não possui grupos, pode cadastrar'); + setJaTemGrupo(false); + setGrupoExistente(null); + } + } catch (error) { + console.error('❌ Erro ao verificar grupos existentes:', error); + setJaTemGrupo(false); + } finally { + setVerificandoGrupos(false); + } + }; + + useEffect(() => { + verificarGruposExistentes(); + }, [userEmail]); + const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); + if (jaTemGrupo) { + toast({ + title: 'Atenção', + description: 'Você já possui um grupo cadastrado', + variant: 'destructive', + }); + return; + } + if (!nomeGrupo.trim()) { toast({ title: 'Erro', @@ -55,7 +97,7 @@ const CreateGroupFormSimple = ({ userEmail, onSuccess }: CreateGroupFormProps) = if (!instanciaInfo.hasInstance) { setMensagemStatus({ tipo: 'error', - texto: 'Você precisa ter uma instância do WhatsApp conectada. Acesse o menu "Conectar WhatsApp" primeiro.' + texto: 'Você precisa ter uma instância do WhatsApp conectada. Acesse o menu "WhatsApp" primeiro.' }); return; } @@ -73,7 +115,7 @@ const CreateGroupFormSimple = ({ userEmail, onSuccess }: CreateGroupFormProps) = await createWorkflowInN8n(userEmail); - // AGORA SIM: Ativar workflow (webhook ativarworkflow) APENAS NO MOMENTO DE CADASTRAR GRUPO + // Ativar workflow console.log('🔔 [GRUPO] Enviando webhook ativarworkflow no momento do cadastro do grupo'); setMensagemStatus({ tipo: 'info', texto: 'Ativando workflow...' }); @@ -87,7 +129,7 @@ const CreateGroupFormSimple = ({ userEmail, onSuccess }: CreateGroupFormProps) = // Continua mesmo se o webhook falhar } - // AGORA SIM: Enviar webhook para N8N configurar webhook da Evolution API APENAS NO MOMENTO DE CADASTRAR GRUPO + // Enviar webhook para N8N configurar webhook da Evolution API console.log('🔔 [GRUPO] Enviando webhook de configuração no momento do cadastro do grupo'); setMensagemStatus({ tipo: 'info', texto: 'Configurando webhook...' }); @@ -114,6 +156,9 @@ const CreateGroupFormSimple = ({ userEmail, onSuccess }: CreateGroupFormProps) = // Limpar formulário setNomeGrupo(''); + // Atualizar estado para refletir que agora tem grupo + setJaTemGrupo(true); + // Atualizar lista de grupos onSuccess(); @@ -134,48 +179,90 @@ const CreateGroupFormSimple = ({ userEmail, onSuccess }: CreateGroupFormProps) = } }; + if (verificandoGrupos) { + return ( + + + Cadastrar novo grupo + + Verificando seus grupos existentes... + + + +
+ + Carregando... +
+
+
+ ); + } + return ( Cadastrar novo grupo - Cadastre um grupo do WhatsApp para receber notificações de suas transações + {jaTemGrupo + ? 'Você já possui um grupo cadastrado' + : 'Cadastre um grupo do WhatsApp para receber notificações de suas transações' + } -
-
- - setNomeGrupo(e.target.value)} - disabled={carregando} - /> -
+ {jaTemGrupo && grupoExistente ? ( + + + + Grupo já cadastrado: {grupoExistente.nome_grupo || 'Grupo sem nome'} +
+ + Status: {grupoExistente.status || 'pendente'} + {grupoExistente.remote_jid && grupoExistente.remote_jid !== '' && ( + • ID: {grupoExistente.remote_jid} + )} + +
+
+ ) : ( + +
+ + setNomeGrupo(e.target.value)} + disabled={carregando || jaTemGrupo} + /> +
- {mensagemStatus && ( - - {mensagemStatus.tipo === 'error' && } - {mensagemStatus.tipo === 'success' && } - {mensagemStatus.tipo === 'info' && } - {mensagemStatus.texto} - - )} - - -
+ + + + )}
);