Feat: Disable group creation if group exists
Disable the "Cadastrar Grupo" button and the input field for the group name if the user already has a group registered.
This commit is contained in:
parent
1690076355
commit
05a8186a19
@ -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<any>(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 <LoadingState message="Verificando instância WhatsApp..." />;
|
||||
if (checkingExistingInstance || verificandoGrupos) {
|
||||
return <LoadingState message="Verificando instância WhatsApp e grupos existentes..." />;
|
||||
}
|
||||
|
||||
// A lógica agora é a mesma da outra página: `hasExistingInstance`
|
||||
//if (!hasExistingInstance) {
|
||||
// return <NoInstanceState userInstance={existingInstanceData} />;
|
||||
//}
|
||||
// Se já tem grupo, mostrar informação
|
||||
if (jaTemGrupo && grupoExistente) {
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Cadastrar novo grupo</CardTitle>
|
||||
<CardDescription>
|
||||
Você já possui um grupo cadastrado
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Alert>
|
||||
<Info className="h-4 w-4" />
|
||||
<AlertDescription>
|
||||
<strong>Grupo já cadastrado:</strong> {grupoExistente.nome_grupo || 'Grupo sem nome'}
|
||||
<br />
|
||||
<span className="text-sm text-muted-foreground">
|
||||
Status: {grupoExistente.status || 'pendente'}
|
||||
{grupoExistente.remote_jid && grupoExistente.remote_jid !== '' && (
|
||||
<span> • ID: {grupoExistente.remote_jid}</span>
|
||||
)}
|
||||
</span>
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
// Se não tem instância conectada, mostrar estado de sem instância
|
||||
if (!hasExistingInstance) {
|
||||
return <NoInstanceState userInstance={existingInstanceData} />;
|
||||
}
|
||||
|
||||
const handleSubmit = (nomeGrupo: string) => {
|
||||
handleCadastrarGrupo(nomeGrupo, existingInstanceData);
|
||||
|
||||
@ -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<any>(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 (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Cadastrar novo grupo</CardTitle>
|
||||
<CardDescription>
|
||||
Verificando seus grupos existentes...
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="flex items-center justify-center p-4">
|
||||
<Loader2 className="h-6 w-6 animate-spin mr-2" />
|
||||
<span>Carregando...</span>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Cadastrar novo grupo</CardTitle>
|
||||
<CardDescription>
|
||||
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'
|
||||
}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="nomeGrupo">Nome do grupo</Label>
|
||||
<Input
|
||||
id="nomeGrupo"
|
||||
type="text"
|
||||
placeholder="Digite o nome do grupo do WhatsApp"
|
||||
value={nomeGrupo}
|
||||
onChange={(e) => setNomeGrupo(e.target.value)}
|
||||
disabled={carregando}
|
||||
/>
|
||||
</div>
|
||||
{jaTemGrupo && grupoExistente ? (
|
||||
<Alert>
|
||||
<Info className="h-4 w-4" />
|
||||
<AlertDescription>
|
||||
<strong>Grupo já cadastrado:</strong> {grupoExistente.nome_grupo || 'Grupo sem nome'}
|
||||
<br />
|
||||
<span className="text-sm text-muted-foreground">
|
||||
Status: {grupoExistente.status || 'pendente'}
|
||||
{grupoExistente.remote_jid && grupoExistente.remote_jid !== '' && (
|
||||
<span> • ID: {grupoExistente.remote_jid}</span>
|
||||
)}
|
||||
</span>
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
) : (
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="nomeGrupo">Nome do grupo</Label>
|
||||
<Input
|
||||
id="nomeGrupo"
|
||||
type="text"
|
||||
placeholder="Digite o nome do grupo do WhatsApp"
|
||||
value={nomeGrupo}
|
||||
onChange={(e) => setNomeGrupo(e.target.value)}
|
||||
disabled={carregando || jaTemGrupo}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{mensagemStatus && (
|
||||
<Alert variant={mensagemStatus.tipo === 'error' ? 'destructive' : 'default'}>
|
||||
{mensagemStatus.tipo === 'error' && <AlertCircle className="h-4 w-4" />}
|
||||
{mensagemStatus.tipo === 'success' && <CheckCircle2 className="h-4 w-4" />}
|
||||
{mensagemStatus.tipo === 'info' && <Loader2 className="h-4 w-4 animate-spin" />}
|
||||
<AlertDescription>{mensagemStatus.texto}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<Button type="submit" disabled={carregando || !nomeGrupo.trim()}>
|
||||
{carregando ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
Cadastrando...
|
||||
</>
|
||||
) : (
|
||||
'Cadastrar grupo'
|
||||
{mensagemStatus && (
|
||||
<Alert variant={mensagemStatus.tipo === 'error' ? 'destructive' : 'default'}>
|
||||
{mensagemStatus.tipo === 'error' && <AlertCircle className="h-4 w-4" />}
|
||||
{mensagemStatus.tipo === 'success' && <CheckCircle2 className="h-4 w-4" />}
|
||||
{mensagemStatus.tipo === 'info' && <Loader2 className="h-4 w-4 animate-spin" />}
|
||||
<AlertDescription>{mensagemStatus.texto}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
</Button>
|
||||
</form>
|
||||
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={carregando || !nomeGrupo.trim() || jaTemGrupo}
|
||||
className="w-full"
|
||||
>
|
||||
{carregando ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
Cadastrando...
|
||||
</>
|
||||
) : (
|
||||
'Cadastrar grupo'
|
||||
)}
|
||||
</Button>
|
||||
</form>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
|
||||
Loading…
Reference in New Issue
Block a user