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 { useState, useEffect } from 'react';
|
||||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||||
import { Input } from '@/components/ui/input';
|
import { Input } from '@/components/ui/input';
|
||||||
@ -25,15 +26,17 @@ const CreateInstanceForm = ({
|
|||||||
const [phoneNumber, setPhoneNumber] = useState('');
|
const [phoneNumber, setPhoneNumber] = useState('');
|
||||||
const [hasExistingInstance, setHasExistingInstance] = useState(false);
|
const [hasExistingInstance, setHasExistingInstance] = useState(false);
|
||||||
const [checkingExistingInstance, setCheckingExistingInstance] = useState(true);
|
const [checkingExistingInstance, setCheckingExistingInstance] = useState(true);
|
||||||
|
const [existingInstanceData, setExistingInstanceData] = useState<any>(null);
|
||||||
const currentUserId = localStorage.getItem('userId') || '';
|
const currentUserId = localStorage.getItem('userId') || '';
|
||||||
const userEmail = (localStorage.getItem('userEmail') || '').toLowerCase();
|
const userEmail = (localStorage.getItem('userEmail') || '').toLowerCase();
|
||||||
|
|
||||||
const instanceName = userEmail;
|
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(() => {
|
useEffect(() => {
|
||||||
const checkExistingInstance = async () => {
|
const checkExistingInstance = async () => {
|
||||||
if (!userEmail) {
|
if (!userEmail) {
|
||||||
|
console.log('❌ Email do usuário não encontrado');
|
||||||
setCheckingExistingInstance(false);
|
setCheckingExistingInstance(false);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@ -44,19 +47,27 @@ const CreateInstanceForm = ({
|
|||||||
|
|
||||||
console.log('📋 Dados da instância encontrados:', existingInstance);
|
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 = !!(
|
const hasValidInstance = !!(
|
||||||
existingInstance &&
|
existingInstance &&
|
||||||
existingInstance.instancia_zap &&
|
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);
|
setHasExistingInstance(hasValidInstance);
|
||||||
|
setExistingInstanceData(existingInstance);
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('❌ Erro ao verificar instância existente:', error);
|
console.error('❌ Erro ao verificar instância existente:', error);
|
||||||
setHasExistingInstance(false);
|
setHasExistingInstance(false);
|
||||||
|
setExistingInstanceData(null);
|
||||||
} finally {
|
} finally {
|
||||||
setCheckingExistingInstance(false);
|
setCheckingExistingInstance(false);
|
||||||
}
|
}
|
||||||
@ -166,6 +177,10 @@ const CreateInstanceForm = ({
|
|||||||
|
|
||||||
// 5. Atualizar estado para evitar nova criação
|
// 5. Atualizar estado para evitar nova criação
|
||||||
setHasExistingInstance(true);
|
setHasExistingInstance(true);
|
||||||
|
setExistingInstanceData({
|
||||||
|
instancia_zap: instanceName,
|
||||||
|
status_instancia: 'conectado'
|
||||||
|
});
|
||||||
|
|
||||||
// 6. Notificar componente pai
|
// 6. Notificar componente pai
|
||||||
onInstanceCreated(newInstance);
|
onInstanceCreated(newInstance);
|
||||||
@ -216,7 +231,7 @@ const CreateInstanceForm = ({
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (hasExistingInstance) {
|
if (hasExistingInstance && existingInstanceData) {
|
||||||
return (
|
return (
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
@ -233,13 +248,16 @@ const CreateInstanceForm = ({
|
|||||||
<AlertCircle className="h-4 w-4" />
|
<AlertCircle className="h-4 w-4" />
|
||||||
<AlertDescription>
|
<AlertDescription>
|
||||||
Apenas uma instância WhatsApp por usuário é permitida.
|
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>
|
</AlertDescription>
|
||||||
</Alert>
|
</Alert>
|
||||||
|
|
||||||
<div className="mt-4 p-4 bg-green-50 border border-green-200 rounded">
|
<div className="mt-4 p-4 bg-green-50 border border-green-200 rounded">
|
||||||
<p className="text-green-800 text-sm">
|
<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>
|
||||||
<p className="text-green-700 text-sm mt-1">
|
<p className="text-green-700 text-sm mt-1">
|
||||||
Para gerenciar sua instância, utilize os botões na lista de instâncias abaixo.
|
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;
|
whatsapp: string | null;
|
||||||
} | null>(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(() => {
|
useEffect(() => {
|
||||||
const checkUserInstance = async () => {
|
const checkUserInstance = async () => {
|
||||||
if (!userEmail) {
|
if (!userEmail) {
|
||||||
@ -45,11 +45,13 @@ const CreateGroupForm = ({ userEmail, onSuccess }: CreateGroupFormProps) => {
|
|||||||
console.log('📋 Dados da instância encontrados:', instanceData);
|
console.log('📋 Dados da instância encontrados:', instanceData);
|
||||||
|
|
||||||
if (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 = !!(
|
const hasValidInstance = !!(
|
||||||
instanceData &&
|
instanceData &&
|
||||||
instanceData.instancia_zap &&
|
instanceData.instancia_zap &&
|
||||||
instanceData.instancia_zap.trim() !== '' &&
|
instanceData.instancia_zap.trim() !== '' &&
|
||||||
|
instanceData.instancia_zap !== 'null' &&
|
||||||
|
instanceData.instancia_zap !== null &&
|
||||||
instanceData.status_instancia === 'conectado'
|
instanceData.status_instancia === 'conectado'
|
||||||
);
|
);
|
||||||
|
|
||||||
@ -59,13 +61,8 @@ const CreateGroupForm = ({ userEmail, onSuccess }: CreateGroupFormProps) => {
|
|||||||
hasValidInstance
|
hasValidInstance
|
||||||
});
|
});
|
||||||
|
|
||||||
if (hasValidInstance) {
|
setHasWhatsAppInstance(hasValidInstance);
|
||||||
setHasWhatsAppInstance(true);
|
setUserInstance(instanceData);
|
||||||
setUserInstance(instanceData);
|
|
||||||
} else {
|
|
||||||
setHasWhatsAppInstance(false);
|
|
||||||
setUserInstance(instanceData);
|
|
||||||
}
|
|
||||||
} else {
|
} else {
|
||||||
console.log('❌ Nenhuma instância encontrada');
|
console.log('❌ Nenhuma instância encontrada');
|
||||||
setHasWhatsAppInstance(false);
|
setHasWhatsAppInstance(false);
|
||||||
@ -204,7 +201,7 @@ const CreateGroupForm = ({ userEmail, onSuccess }: CreateGroupFormProps) => {
|
|||||||
<AlertDescription>
|
<AlertDescription>
|
||||||
{userInstance && userInstance.instancia_zap && userInstance.status_instancia !== 'conectado' ? (
|
{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.
|
Acesse o menu "Conectar WhatsApp" e escaneie o QR Code para conectar sua instância.
|
||||||
<br />
|
<br />
|
||||||
<span className="text-sm text-gray-600 mt-2 block">
|
<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 { useWhatsAppActions } from '@/hooks/useWhatsAppActions';
|
||||||
import { useWhatsAppInstance, WHATSAPP_INSTANCE_KEY } from '@/hooks/whatsApp/useWhatsAppInstance';
|
import { useWhatsAppInstance, WHATSAPP_INSTANCE_KEY } from '@/hooks/whatsApp/useWhatsAppInstance';
|
||||||
import { usePeriodicStatusCheck } from '@/hooks/whatsApp/usePeriodicStatusCheck';
|
import { usePeriodicStatusCheck } from '@/hooks/whatsApp/usePeriodicStatusCheck';
|
||||||
|
import { getUserWhatsAppInstance } from '@/services/whatsAppInstanceService';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { RefreshCw } from 'lucide-react';
|
import { RefreshCw } from 'lucide-react';
|
||||||
import { useState } from 'react';
|
import { useState, useEffect } from 'react';
|
||||||
|
|
||||||
const WhatsApp = () => {
|
const WhatsApp = () => {
|
||||||
const {
|
const {
|
||||||
@ -49,8 +50,54 @@ const WhatsApp = () => {
|
|||||||
clearInstanceName
|
clearInstanceName
|
||||||
} = useWhatsAppInstance(currentUserId, addInstance);
|
} = useWhatsAppInstance(currentUserId, addInstance);
|
||||||
|
|
||||||
// Toggle for showing the creation form
|
// State para controlar se deve mostrar o formulário de criação
|
||||||
const [showCreateForm, setShowCreateForm] = useState(!instanceFound && instances.length === 0);
|
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
|
// Set up periodic status checking only after instances are loaded
|
||||||
usePeriodicStatusCheck(instances.length, checkAllInstancesStatus);
|
usePeriodicStatusCheck(instances.length, checkAllInstancesStatus);
|
||||||
@ -60,6 +107,7 @@ const WhatsApp = () => {
|
|||||||
console.log('🎉 Nova instância criada:', newInstance);
|
console.log('🎉 Nova instância criada:', newInstance);
|
||||||
addInstance(newInstance);
|
addInstance(newInstance);
|
||||||
setInstanceFound(true);
|
setInstanceFound(true);
|
||||||
|
setHasValidInstance(true);
|
||||||
setShowCreateForm(false);
|
setShowCreateForm(false);
|
||||||
|
|
||||||
// Salvar o nome da instância no localStorage para uso futuro
|
// Salvar o nome da instância no localStorage para uso futuro
|
||||||
@ -87,19 +135,27 @@ const WhatsApp = () => {
|
|||||||
if (instanceToDelete) {
|
if (instanceToDelete) {
|
||||||
handleDeleteInstance(instanceId, instanceToDelete.instanceName);
|
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) {
|
if (instanceToDelete.instanceName === instanceName) {
|
||||||
clearInstanceName();
|
clearInstanceName();
|
||||||
|
setHasValidInstance(false);
|
||||||
setShowCreateForm(true);
|
setShowCreateForm(true);
|
||||||
}
|
}
|
||||||
} else {
|
} 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
|
// Check if we have any instances to show
|
||||||
const hasInstances = Array.isArray(instances) && instances.length > 0;
|
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 (
|
return (
|
||||||
<Layout>
|
<Layout>
|
||||||
@ -126,46 +182,40 @@ const WhatsApp = () => {
|
|||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{isLoading ? (
|
{/* Show create form if user doesn't have a valid instance */}
|
||||||
<LoadingState />
|
{showCreateForm && (
|
||||||
) : (
|
<CreateInstanceForm
|
||||||
<>
|
onInstanceCreated={handleInstanceCreated}
|
||||||
{/* Always show create form if showCreateForm is true */}
|
initialInstanceName={instanceName}
|
||||||
{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}
|
|
||||||
/>
|
|
||||||
</>
|
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{/* 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 */}
|
{/* QR Code Dialog */}
|
||||||
<QrCodeDialog
|
<QrCodeDialog
|
||||||
open={qrDialogOpen}
|
open={qrDialogOpen}
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user