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 { useGroupCreation } from '@/hooks/whatsappGroups/useGroupCreation';
|
||||||
|
import { listarGruposWhatsApp } from '@/services/gruposWhatsAppService';
|
||||||
import LoadingState from './LoadingState';
|
import LoadingState from './LoadingState';
|
||||||
import NoInstanceState from './NoInstanceState';
|
import NoInstanceState from './NoInstanceState';
|
||||||
import GroupCreationForm from './GroupCreationForm';
|
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 {
|
interface CreateGroupFormProps {
|
||||||
userEmail: string;
|
userEmail: string;
|
||||||
@ -12,7 +16,10 @@ interface CreateGroupFormProps {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const CreateGroupForm = ({ userEmail, onSuccess }: 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 {
|
const {
|
||||||
hasExistingInstance,
|
hasExistingInstance,
|
||||||
checkingExistingInstance,
|
checkingExistingInstance,
|
||||||
@ -22,18 +29,74 @@ const CreateGroupForm = ({ userEmail, onSuccess }: CreateGroupFormProps) => {
|
|||||||
|
|
||||||
const { cadastrando, handleCadastrarGrupo } = useGroupCreation(userEmail, onSuccess);
|
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(() => {
|
useEffect(() => {
|
||||||
recheckInstance();
|
recheckInstance();
|
||||||
}, [userEmail]); // Re-verifica quando o email muda
|
verificarGruposExistentes();
|
||||||
|
}, [userEmail]);
|
||||||
|
|
||||||
if (checkingExistingInstance) {
|
if (checkingExistingInstance || verificandoGrupos) {
|
||||||
return <LoadingState message="Verificando instância WhatsApp..." />;
|
return <LoadingState message="Verificando instância WhatsApp e grupos existentes..." />;
|
||||||
}
|
}
|
||||||
|
|
||||||
// A lógica agora é a mesma da outra página: `hasExistingInstance`
|
// Se já tem grupo, mostrar informação
|
||||||
//if (!hasExistingInstance) {
|
if (jaTemGrupo && grupoExistente) {
|
||||||
// return <NoInstanceState userInstance={existingInstanceData} />;
|
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) => {
|
const handleSubmit = (nomeGrupo: string) => {
|
||||||
handleCadastrarGrupo(nomeGrupo, existingInstanceData);
|
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 { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { Input } from '@/components/ui/input';
|
import { Input } from '@/components/ui/input';
|
||||||
import { Label } from '@/components/ui/label';
|
import { Label } from '@/components/ui/label';
|
||||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
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 { useToast } from '@/hooks/use-toast';
|
||||||
import { verificarInstanciaWhatsApp } from '@/services/gruposWhatsAppService';
|
import { verificarInstanciaWhatsApp, listarGruposWhatsApp } from '@/services/gruposWhatsAppService';
|
||||||
import { findOrCreateWhatsAppGroup } from '@/services/whatsAppGroupsService';
|
import { findOrCreateWhatsAppGroup } from '@/services/whatsAppGroupsService';
|
||||||
import { createWorkflowInN8n } from '@/services/n8nWorkflowService';
|
import { createWorkflowInN8n } from '@/services/n8nWorkflowService';
|
||||||
import { createEvolutionWebhook } from '@/services/whatsApp/webhookService';
|
import { createEvolutionWebhook } from '@/services/whatsApp/webhookService';
|
||||||
@ -22,6 +22,9 @@ const CreateGroupFormSimple = ({ userEmail, onSuccess }: CreateGroupFormProps) =
|
|||||||
const { toast } = useToast();
|
const { toast } = useToast();
|
||||||
const [nomeGrupo, setNomeGrupo] = useState('');
|
const [nomeGrupo, setNomeGrupo] = useState('');
|
||||||
const [carregando, setCarregando] = useState(false);
|
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 [webhookEnviado, setWebhookEnviado] = useState(false);
|
||||||
const [workflowAtivado, setWorkflowAtivado] = useState(false);
|
const [workflowAtivado, setWorkflowAtivado] = useState(false);
|
||||||
const [mensagemStatus, setMensagemStatus] = useState<{
|
const [mensagemStatus, setMensagemStatus] = useState<{
|
||||||
@ -29,9 +32,48 @@ const CreateGroupFormSimple = ({ userEmail, onSuccess }: CreateGroupFormProps) =
|
|||||||
texto: string;
|
texto: string;
|
||||||
} | null>(null);
|
} | 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) => {
|
const handleSubmit = async (e: React.FormEvent) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
|
|
||||||
|
if (jaTemGrupo) {
|
||||||
|
toast({
|
||||||
|
title: 'Atenção',
|
||||||
|
description: 'Você já possui um grupo cadastrado',
|
||||||
|
variant: 'destructive',
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (!nomeGrupo.trim()) {
|
if (!nomeGrupo.trim()) {
|
||||||
toast({
|
toast({
|
||||||
title: 'Erro',
|
title: 'Erro',
|
||||||
@ -55,7 +97,7 @@ const CreateGroupFormSimple = ({ userEmail, onSuccess }: CreateGroupFormProps) =
|
|||||||
if (!instanciaInfo.hasInstance) {
|
if (!instanciaInfo.hasInstance) {
|
||||||
setMensagemStatus({
|
setMensagemStatus({
|
||||||
tipo: 'error',
|
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;
|
return;
|
||||||
}
|
}
|
||||||
@ -73,7 +115,7 @@ const CreateGroupFormSimple = ({ userEmail, onSuccess }: CreateGroupFormProps) =
|
|||||||
|
|
||||||
await createWorkflowInN8n(userEmail);
|
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');
|
console.log('🔔 [GRUPO] Enviando webhook ativarworkflow no momento do cadastro do grupo');
|
||||||
setMensagemStatus({ tipo: 'info', texto: 'Ativando workflow...' });
|
setMensagemStatus({ tipo: 'info', texto: 'Ativando workflow...' });
|
||||||
|
|
||||||
@ -87,7 +129,7 @@ const CreateGroupFormSimple = ({ userEmail, onSuccess }: CreateGroupFormProps) =
|
|||||||
// Continua mesmo se o webhook falhar
|
// 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');
|
console.log('🔔 [GRUPO] Enviando webhook de configuração no momento do cadastro do grupo');
|
||||||
setMensagemStatus({ tipo: 'info', texto: 'Configurando webhook...' });
|
setMensagemStatus({ tipo: 'info', texto: 'Configurando webhook...' });
|
||||||
|
|
||||||
@ -114,6 +156,9 @@ const CreateGroupFormSimple = ({ userEmail, onSuccess }: CreateGroupFormProps) =
|
|||||||
// Limpar formulário
|
// Limpar formulário
|
||||||
setNomeGrupo('');
|
setNomeGrupo('');
|
||||||
|
|
||||||
|
// Atualizar estado para refletir que agora tem grupo
|
||||||
|
setJaTemGrupo(true);
|
||||||
|
|
||||||
// Atualizar lista de grupos
|
// Atualizar lista de grupos
|
||||||
onSuccess();
|
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 (
|
return (
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle>Cadastrar novo grupo</CardTitle>
|
<CardTitle>Cadastrar novo grupo</CardTitle>
|
||||||
<CardDescription>
|
<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>
|
</CardDescription>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent>
|
||||||
<form onSubmit={handleSubmit} className="space-y-4">
|
{jaTemGrupo && grupoExistente ? (
|
||||||
<div className="space-y-2">
|
<Alert>
|
||||||
<Label htmlFor="nomeGrupo">Nome do grupo</Label>
|
<Info className="h-4 w-4" />
|
||||||
<Input
|
<AlertDescription>
|
||||||
id="nomeGrupo"
|
<strong>Grupo já cadastrado:</strong> {grupoExistente.nome_grupo || 'Grupo sem nome'}
|
||||||
type="text"
|
<br />
|
||||||
placeholder="Digite o nome do grupo do WhatsApp"
|
<span className="text-sm text-muted-foreground">
|
||||||
value={nomeGrupo}
|
Status: {grupoExistente.status || 'pendente'}
|
||||||
onChange={(e) => setNomeGrupo(e.target.value)}
|
{grupoExistente.remote_jid && grupoExistente.remote_jid !== '' && (
|
||||||
disabled={carregando}
|
<span> • ID: {grupoExistente.remote_jid}</span>
|
||||||
/>
|
)}
|
||||||
</div>
|
</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 && (
|
{mensagemStatus && (
|
||||||
<Alert variant={mensagemStatus.tipo === 'error' ? 'destructive' : 'default'}>
|
<Alert variant={mensagemStatus.tipo === 'error' ? 'destructive' : 'default'}>
|
||||||
{mensagemStatus.tipo === 'error' && <AlertCircle className="h-4 w-4" />}
|
{mensagemStatus.tipo === 'error' && <AlertCircle className="h-4 w-4" />}
|
||||||
{mensagemStatus.tipo === 'success' && <CheckCircle2 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" />}
|
{mensagemStatus.tipo === 'info' && <Loader2 className="h-4 w-4 animate-spin" />}
|
||||||
<AlertDescription>{mensagemStatus.texto}</AlertDescription>
|
<AlertDescription>{mensagemStatus.texto}</AlertDescription>
|
||||||
</Alert>
|
</Alert>
|
||||||
)}
|
|
||||||
|
|
||||||
<Button type="submit" disabled={carregando || !nomeGrupo.trim()}>
|
|
||||||
{carregando ? (
|
|
||||||
<>
|
|
||||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
|
||||||
Cadastrando...
|
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
'Cadastrar grupo'
|
|
||||||
)}
|
)}
|
||||||
</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>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
);
|
);
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user