Fix: Incorrect instance detection
The previous fix for instance detection was not fully effective. This commit further refines the logic in `src/components/whatsapp/CreateInstanceForm.tsx` and `src/components/whatsappGroups/CreateGroupForm.tsx` to ensure that the app correctly identifies existing WhatsApp instances and prevents the creation of duplicate instances or groups.
This commit is contained in:
parent
be3ceeaeb2
commit
9a3e2ac4fb
@ -1,3 +1,4 @@
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Input } from '@/components/ui/input';
|
||||
@ -25,15 +26,17 @@ const CreateInstanceForm = ({
|
||||
const [phoneNumber, setPhoneNumber] = useState('');
|
||||
const [hasExistingInstance, setHasExistingInstance] = useState(false);
|
||||
const [checkingExistingInstance, setCheckingExistingInstance] = useState(true);
|
||||
const [existingInstanceData, setExistingInstanceData] = useState<any>(null);
|
||||
const currentUserId = localStorage.getItem('userId') || '';
|
||||
const userEmail = (localStorage.getItem('userEmail') || '').toLowerCase();
|
||||
|
||||
const instanceName = userEmail;
|
||||
|
||||
// Verificar se o usuário já tem uma instância - verificação mais rigorosa
|
||||
// Verificar se o usuário já tem uma instância
|
||||
useEffect(() => {
|
||||
const checkExistingInstance = async () => {
|
||||
if (!userEmail) {
|
||||
console.log('❌ Email do usuário não encontrado');
|
||||
setCheckingExistingInstance(false);
|
||||
return;
|
||||
}
|
||||
@ -44,19 +47,27 @@ const CreateInstanceForm = ({
|
||||
|
||||
console.log('📋 Dados da instância encontrados:', existingInstance);
|
||||
|
||||
// Verificação mais rigorosa - deve ter instancia_zap E não pode estar vazio
|
||||
// Verificação rigorosa - deve ter instancia_zap válida
|
||||
const hasValidInstance = !!(
|
||||
existingInstance &&
|
||||
existingInstance.instancia_zap &&
|
||||
existingInstance.instancia_zap.trim() !== ''
|
||||
existingInstance.instancia_zap.trim() !== '' &&
|
||||
existingInstance.instancia_zap !== 'null' &&
|
||||
existingInstance.instancia_zap !== null
|
||||
);
|
||||
|
||||
console.log('✅ Usuário possui instância válida:', hasValidInstance);
|
||||
console.log('✅ Usuário possui instância válida:', hasValidInstance, {
|
||||
instancia_zap: existingInstance?.instancia_zap,
|
||||
status_instancia: existingInstance?.status_instancia
|
||||
});
|
||||
|
||||
setHasExistingInstance(hasValidInstance);
|
||||
setExistingInstanceData(existingInstance);
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ Erro ao verificar instância existente:', error);
|
||||
setHasExistingInstance(false);
|
||||
setExistingInstanceData(null);
|
||||
} finally {
|
||||
setCheckingExistingInstance(false);
|
||||
}
|
||||
@ -166,6 +177,10 @@ const CreateInstanceForm = ({
|
||||
|
||||
// 5. Atualizar estado para evitar nova criação
|
||||
setHasExistingInstance(true);
|
||||
setExistingInstanceData({
|
||||
instancia_zap: instanceName,
|
||||
status_instancia: 'conectado'
|
||||
});
|
||||
|
||||
// 6. Notificar componente pai
|
||||
onInstanceCreated(newInstance);
|
||||
@ -216,7 +231,7 @@ const CreateInstanceForm = ({
|
||||
);
|
||||
}
|
||||
|
||||
if (hasExistingInstance) {
|
||||
if (hasExistingInstance && existingInstanceData) {
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
@ -233,13 +248,16 @@ const CreateInstanceForm = ({
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription>
|
||||
Apenas uma instância WhatsApp por usuário é permitida.
|
||||
Sua instância atual: <strong>{instanceName}</strong>
|
||||
Sua instância atual: <strong>{existingInstanceData.instancia_zap}</strong>
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
|
||||
<div className="mt-4 p-4 bg-green-50 border border-green-200 rounded">
|
||||
<p className="text-green-800 text-sm">
|
||||
<strong>✓ Instância ativa:</strong> {instanceName}
|
||||
<strong>✓ Instância ativa:</strong> {existingInstanceData.instancia_zap}
|
||||
</p>
|
||||
<p className="text-green-700 text-sm mt-1">
|
||||
<strong>Status:</strong> {existingInstanceData.status_instancia || 'conectado'}
|
||||
</p>
|
||||
<p className="text-green-700 text-sm mt-1">
|
||||
Para gerenciar sua instância, utilize os botões na lista de instâncias abaixo.
|
||||
|
||||
@ -28,7 +28,7 @@ const CreateGroupForm = ({ userEmail, onSuccess }: CreateGroupFormProps) => {
|
||||
whatsapp: string | null;
|
||||
} | null>(null);
|
||||
|
||||
// Verificar se o usuário tem instância WhatsApp CONECTADA - verificação mais rigorosa
|
||||
// Verificar se o usuário tem instância WhatsApp CONECTADA
|
||||
useEffect(() => {
|
||||
const checkUserInstance = async () => {
|
||||
if (!userEmail) {
|
||||
@ -45,11 +45,13 @@ const CreateGroupForm = ({ userEmail, onSuccess }: CreateGroupFormProps) => {
|
||||
console.log('📋 Dados da instância encontrados:', instanceData);
|
||||
|
||||
if (instanceData) {
|
||||
// Verificação mais rigorosa: deve ter instancia_zap E status conectado
|
||||
// Verificação rigorosa: deve ter instancia_zap válida E status conectado
|
||||
const hasValidInstance = !!(
|
||||
instanceData &&
|
||||
instanceData.instancia_zap &&
|
||||
instanceData.instancia_zap.trim() !== '' &&
|
||||
instanceData.instancia_zap !== 'null' &&
|
||||
instanceData.instancia_zap !== null &&
|
||||
instanceData.status_instancia === 'conectado'
|
||||
);
|
||||
|
||||
@ -59,13 +61,8 @@ const CreateGroupForm = ({ userEmail, onSuccess }: CreateGroupFormProps) => {
|
||||
hasValidInstance
|
||||
});
|
||||
|
||||
if (hasValidInstance) {
|
||||
setHasWhatsAppInstance(true);
|
||||
setUserInstance(instanceData);
|
||||
} else {
|
||||
setHasWhatsAppInstance(false);
|
||||
setUserInstance(instanceData);
|
||||
}
|
||||
setHasWhatsAppInstance(hasValidInstance);
|
||||
setUserInstance(instanceData);
|
||||
} else {
|
||||
console.log('❌ Nenhuma instância encontrada');
|
||||
setHasWhatsAppInstance(false);
|
||||
@ -204,7 +201,7 @@ const CreateGroupForm = ({ userEmail, onSuccess }: CreateGroupFormProps) => {
|
||||
<AlertDescription>
|
||||
{userInstance && userInstance.instancia_zap && userInstance.status_instancia !== 'conectado' ? (
|
||||
<>
|
||||
Sua instância WhatsApp está <strong>desconectada</strong>.
|
||||
Sua instância WhatsApp <strong>{userInstance.instancia_zap}</strong> está <strong>desconectada</strong>.
|
||||
Acesse o menu "Conectar WhatsApp" e escaneie o QR Code para conectar sua instância.
|
||||
<br />
|
||||
<span className="text-sm text-gray-600 mt-2 block">
|
||||
|
||||
@ -10,9 +10,10 @@ import { useWhatsAppInstances } from '@/hooks/useWhatsAppInstances';
|
||||
import { useWhatsAppActions } from '@/hooks/useWhatsAppActions';
|
||||
import { useWhatsAppInstance, WHATSAPP_INSTANCE_KEY } from '@/hooks/whatsApp/useWhatsAppInstance';
|
||||
import { usePeriodicStatusCheck } from '@/hooks/whatsApp/usePeriodicStatusCheck';
|
||||
import { getUserWhatsAppInstance } from '@/services/whatsAppInstanceService';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { RefreshCw } from 'lucide-react';
|
||||
import { useState } from 'react';
|
||||
import { useState, useEffect } from 'react';
|
||||
|
||||
const WhatsApp = () => {
|
||||
const {
|
||||
@ -49,8 +50,54 @@ const WhatsApp = () => {
|
||||
clearInstanceName
|
||||
} = useWhatsAppInstance(currentUserId, addInstance);
|
||||
|
||||
// Toggle for showing the creation form
|
||||
const [showCreateForm, setShowCreateForm] = useState(!instanceFound && instances.length === 0);
|
||||
// State para controlar se deve mostrar o formulário de criação
|
||||
const [showCreateForm, setShowCreateForm] = useState(false);
|
||||
const [hasValidInstance, setHasValidInstance] = useState(false);
|
||||
const [checkingUserInstance, setCheckingUserInstance] = useState(true);
|
||||
|
||||
const userEmail = localStorage.getItem('userEmail') || '';
|
||||
|
||||
// Verificar se o usuário tem instância válida no banco de dados
|
||||
useEffect(() => {
|
||||
const checkUserInstanceFromDB = async () => {
|
||||
if (!userEmail) {
|
||||
setCheckingUserInstance(false);
|
||||
setShowCreateForm(true);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
console.log('🔍 Verificando instância do usuário no banco:', userEmail);
|
||||
const instanceData = await getUserWhatsAppInstance(userEmail);
|
||||
|
||||
const hasInstance = !!(
|
||||
instanceData &&
|
||||
instanceData.instancia_zap &&
|
||||
instanceData.instancia_zap.trim() !== '' &&
|
||||
instanceData.instancia_zap !== 'null' &&
|
||||
instanceData.instancia_zap !== null
|
||||
);
|
||||
|
||||
console.log('📋 Usuário tem instância válida:', hasInstance, instanceData);
|
||||
|
||||
setHasValidInstance(hasInstance);
|
||||
setShowCreateForm(!hasInstance);
|
||||
|
||||
if (hasInstance) {
|
||||
setInstanceFound(true);
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ Erro ao verificar instância do usuário:', error);
|
||||
setHasValidInstance(false);
|
||||
setShowCreateForm(true);
|
||||
} finally {
|
||||
setCheckingUserInstance(false);
|
||||
}
|
||||
};
|
||||
|
||||
checkUserInstanceFromDB();
|
||||
}, [userEmail, setInstanceFound]);
|
||||
|
||||
// Set up periodic status checking only after instances are loaded
|
||||
usePeriodicStatusCheck(instances.length, checkAllInstancesStatus);
|
||||
@ -60,6 +107,7 @@ const WhatsApp = () => {
|
||||
console.log('🎉 Nova instância criada:', newInstance);
|
||||
addInstance(newInstance);
|
||||
setInstanceFound(true);
|
||||
setHasValidInstance(true);
|
||||
setShowCreateForm(false);
|
||||
|
||||
// Salvar o nome da instância no localStorage para uso futuro
|
||||
@ -87,19 +135,27 @@ const WhatsApp = () => {
|
||||
if (instanceToDelete) {
|
||||
handleDeleteInstance(instanceId, instanceToDelete.instanceName);
|
||||
|
||||
// Se a instância excluída for a atual, limpar o nome salvo
|
||||
// Se a instância excluída for a atual, limpar o nome salvo e permitir criação de nova
|
||||
if (instanceToDelete.instanceName === instanceName) {
|
||||
clearInstanceName();
|
||||
setHasValidInstance(false);
|
||||
setShowCreateForm(true);
|
||||
}
|
||||
} else {
|
||||
console.error(`❌ Instância com ID ${instanceId} não encontrada para exclusão`);
|
||||
console.error(`❌ Inst ncia com ID ${instanceId} não encontrada para exclusão`);
|
||||
}
|
||||
};
|
||||
|
||||
// Check if we have any instances to show
|
||||
const hasInstances = Array.isArray(instances) && instances.length > 0;
|
||||
const userEmail = localStorage.getItem('userEmail') || '';
|
||||
|
||||
if (checkingUserInstance || isLoading) {
|
||||
return (
|
||||
<Layout>
|
||||
<LoadingState message="Verificando suas instâncias..." />
|
||||
</Layout>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Layout>
|
||||
@ -126,46 +182,40 @@ const WhatsApp = () => {
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{isLoading ? (
|
||||
<LoadingState />
|
||||
) : (
|
||||
<>
|
||||
{/* Always show create form if showCreateForm is true */}
|
||||
{showCreateForm && (
|
||||
<CreateInstanceForm
|
||||
onInstanceCreated={handleInstanceCreated}
|
||||
initialInstanceName={instanceName}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Toggle Create Form Button - only show if form is hidden */}
|
||||
{!showCreateForm && (
|
||||
<Button
|
||||
onClick={() => setShowCreateForm(true)}
|
||||
className="mb-4"
|
||||
>
|
||||
Conectar Novo WhatsApp
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{/* Only show stats if instances are available */}
|
||||
{hasInstances && <InstanceStats instances={instances} />}
|
||||
|
||||
{/* List of created instances */}
|
||||
<InstanceList
|
||||
instances={instances}
|
||||
onViewQrCode={handleViewQrCode}
|
||||
onDelete={handleDeleteInstanceWrapper}
|
||||
onRestart={handleRestartInstance}
|
||||
onLogout={handleLogoutInstance}
|
||||
onDisconnect={handleDisconnectInstance}
|
||||
onSetPresence={handleSetPresence}
|
||||
onRefreshInstances={refreshInstances}
|
||||
isRefreshing={isRefreshing}
|
||||
/>
|
||||
</>
|
||||
{/* Show create form if user doesn't have a valid instance */}
|
||||
{showCreateForm && (
|
||||
<CreateInstanceForm
|
||||
onInstanceCreated={handleInstanceCreated}
|
||||
initialInstanceName={instanceName}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Toggle Create Form Button - only show if form is hidden and user has instance */}
|
||||
{!showCreateForm && hasValidInstance && (
|
||||
<Button
|
||||
onClick={() => setShowCreateForm(true)}
|
||||
className="mb-4"
|
||||
>
|
||||
Conectar Novo WhatsApp
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{/* Only show stats if instances are available */}
|
||||
{hasInstances && <InstanceStats instances={instances} />}
|
||||
|
||||
{/* List of created instances */}
|
||||
<InstanceList
|
||||
instances={instances}
|
||||
onViewQrCode={handleViewQrCode}
|
||||
onDelete={handleDeleteInstanceWrapper}
|
||||
onRestart={handleRestartInstance}
|
||||
onLogout={handleLogoutInstance}
|
||||
onDisconnect={handleDisconnectInstance}
|
||||
onSetPresence={handleSetPresence}
|
||||
onRefreshInstances={refreshInstances}
|
||||
isRefreshing={isRefreshing}
|
||||
/>
|
||||
|
||||
{/* QR Code Dialog */}
|
||||
<QrCodeDialog
|
||||
open={qrDialogOpen}
|
||||
|
||||
Loading…
Reference in New Issue
Block a user