Fix WhatsApp instance detection
Centralize instance check, remove debug, and fix UI.
This commit is contained in:
parent
ec9c883bf0
commit
7fbce3ca0b
@ -19,30 +19,29 @@ export const useExistingInstanceCheck = (userEmail: string) => {
|
|||||||
setCheckingExistingInstance(true);
|
setCheckingExistingInstance(true);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
console.log('🔍 [EXISTING_INSTANCE] Verificando se usuário já tem instância CONECTADA:', userEmail);
|
console.log('🔍 [EXISTING_INSTANCE] Verificando instância para:', userEmail);
|
||||||
const existingInstance = await getUserWhatsAppInstance(userEmail);
|
const existingInstance = await getUserWhatsAppInstance(userEmail);
|
||||||
|
|
||||||
console.log('📋 [EXISTING_INSTANCE] Dados da instância encontrados:', existingInstance);
|
console.log('📋 [EXISTING_INSTANCE] Dados retornados:', existingInstance);
|
||||||
|
|
||||||
// Verificação SIMPLES e DIRETA: instancia_zap deve existir E status deve ser 'conectado'
|
// Verificação DIRETA: se existe instancia_zap E status é 'conectado'
|
||||||
const hasValidConnectedInstance = !!(
|
const hasValidInstance = !!(
|
||||||
existingInstance &&
|
existingInstance &&
|
||||||
existingInstance.instancia_zap &&
|
existingInstance.instancia_zap &&
|
||||||
existingInstance.status_instancia === 'conectado'
|
existingInstance.status_instancia === 'conectado'
|
||||||
);
|
);
|
||||||
|
|
||||||
console.log('✅ [EXISTING_INSTANCE] Resultado final da verificação:', {
|
console.log('✅ [EXISTING_INSTANCE] Resultado:', {
|
||||||
|
hasValidInstance,
|
||||||
instancia_zap: existingInstance?.instancia_zap,
|
instancia_zap: existingInstance?.instancia_zap,
|
||||||
status_instancia: existingInstance?.status_instancia,
|
status_instancia: existingInstance?.status_instancia
|
||||||
userEmail: userEmail,
|
|
||||||
hasValidConnectedInstance: hasValidConnectedInstance
|
|
||||||
});
|
});
|
||||||
|
|
||||||
setHasExistingInstance(hasValidConnectedInstance);
|
setHasExistingInstance(hasValidInstance);
|
||||||
setExistingInstanceData(hasValidConnectedInstance ? existingInstance : null);
|
setExistingInstanceData(hasValidInstance ? existingInstance : null);
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('❌ [EXISTING_INSTANCE] Erro ao verificar instância existente:', error);
|
console.error('❌ [EXISTING_INSTANCE] Erro:', error);
|
||||||
setHasExistingInstance(false);
|
setHasExistingInstance(false);
|
||||||
setExistingInstanceData(null);
|
setExistingInstanceData(null);
|
||||||
} finally {
|
} finally {
|
||||||
@ -54,9 +53,8 @@ export const useExistingInstanceCheck = (userEmail: string) => {
|
|||||||
checkExistingInstance();
|
checkExistingInstance();
|
||||||
}, [userEmail]);
|
}, [userEmail]);
|
||||||
|
|
||||||
// Função para forçar re-verificação
|
|
||||||
const recheckInstance = () => {
|
const recheckInstance = () => {
|
||||||
console.log('🔄 [EXISTING_INSTANCE] Forçando re-verificação da instância');
|
console.log('🔄 [EXISTING_INSTANCE] Re-verificação manual');
|
||||||
checkExistingInstance();
|
checkExistingInstance();
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@ -50,7 +50,7 @@ const WhatsApp = () => {
|
|||||||
|
|
||||||
const userEmail = (localStorage.getItem('userEmail') || '').toLowerCase();
|
const userEmail = (localStorage.getItem('userEmail') || '').toLowerCase();
|
||||||
|
|
||||||
// USAR APENAS O HOOK CENTRALIZADO para verificação de instância existente
|
// Hook centralizado para verificação de instância existente
|
||||||
const {
|
const {
|
||||||
hasExistingInstance,
|
hasExistingInstance,
|
||||||
checkingExistingInstance,
|
checkingExistingInstance,
|
||||||
@ -67,7 +67,7 @@ const WhatsApp = () => {
|
|||||||
addInstance(newInstance);
|
addInstance(newInstance);
|
||||||
setInstanceFound(true);
|
setInstanceFound(true);
|
||||||
|
|
||||||
// Atualizar o estado do hook centralizado
|
// Atualizar estado do hook centralizado
|
||||||
setHasExistingInstance(true);
|
setHasExistingInstance(true);
|
||||||
setExistingInstanceData({
|
setExistingInstanceData({
|
||||||
instancia_zap: newInstance.instanceName,
|
instancia_zap: newInstance.instanceName,
|
||||||
@ -83,7 +83,6 @@ const WhatsApp = () => {
|
|||||||
setTimeout(async () => {
|
setTimeout(async () => {
|
||||||
try {
|
try {
|
||||||
await checkAllInstancesStatus();
|
await checkAllInstancesStatus();
|
||||||
// Forçar re-verificação após status check
|
|
||||||
recheckInstance();
|
recheckInstance();
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Error checking status after instance creation:", error);
|
console.error("Error checking status after instance creation:", error);
|
||||||
@ -92,7 +91,7 @@ const WhatsApp = () => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const handleDeleteInstanceWrapper = (instanceId: string) => {
|
const handleDeleteInstanceWrapper = (instanceId: string) => {
|
||||||
console.log(`🗑️ [WHATSAPP] Solicitação de exclusão da instância ID: ${instanceId}`);
|
console.log(`🗑️ [WHATSAPP] Excluindo instância ID: ${instanceId}`);
|
||||||
const instanceToDelete = instances.find(i => i.instanceId === instanceId);
|
const instanceToDelete = instances.find(i => i.instanceId === instanceId);
|
||||||
if (instanceToDelete) {
|
if (instanceToDelete) {
|
||||||
handleDeleteInstance(instanceId, instanceToDelete.instanceName);
|
handleDeleteInstance(instanceId, instanceToDelete.instanceName);
|
||||||
@ -102,14 +101,12 @@ const WhatsApp = () => {
|
|||||||
setHasExistingInstance(false);
|
setHasExistingInstance(false);
|
||||||
setExistingInstanceData(null);
|
setExistingInstanceData(null);
|
||||||
}
|
}
|
||||||
} else {
|
|
||||||
console.error(`❌ [WHATSAPP] Instância com ID ${instanceId} não encontrada para exclusão`);
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const hasInstances = Array.isArray(instances) && instances.length > 0;
|
const hasInstances = Array.isArray(instances) && instances.length > 0;
|
||||||
|
|
||||||
// Mostrar loading enquanto verifica instância existente
|
// Loading enquanto verifica instância
|
||||||
if (checkingExistingInstance || isLoading) {
|
if (checkingExistingInstance || isLoading) {
|
||||||
return (
|
return (
|
||||||
<Layout>
|
<Layout>
|
||||||
@ -118,14 +115,6 @@ const WhatsApp = () => {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log('🔍 [WHATSAPP] Estado atual da verificação FINAL:', {
|
|
||||||
userEmail,
|
|
||||||
hasExistingInstance,
|
|
||||||
existingInstanceData,
|
|
||||||
checkingExistingInstance,
|
|
||||||
'Deve mostrar formulário?': !hasExistingInstance
|
|
||||||
});
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Layout>
|
<Layout>
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
@ -147,29 +136,12 @@ const WhatsApp = () => {
|
|||||||
className="flex items-center gap-2"
|
className="flex items-center gap-2"
|
||||||
>
|
>
|
||||||
<RefreshCw className={`h-4 w-4 ${checkingExistingInstance ? 'animate-spin' : ''}`} />
|
<RefreshCw className={`h-4 w-4 ${checkingExistingInstance ? 'animate-spin' : ''}`} />
|
||||||
Verificar Instância
|
Atualizar
|
||||||
</Button>
|
|
||||||
|
|
||||||
<Button
|
|
||||||
variant="outline"
|
|
||||||
onClick={refreshInstances}
|
|
||||||
disabled={isRefreshing}
|
|
||||||
className="flex items-center gap-2"
|
|
||||||
>
|
|
||||||
<RefreshCw className={`h-4 w-4 ${isRefreshing ? 'animate-spin' : ''}`} />
|
|
||||||
{isRefreshing ? 'Atualizando...' : 'Atualizar Lista'}
|
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* DEBUG: Mostrar estado atual */}
|
{/* Formulário de criação - APENAS se NÃO tiver instância conectada */}
|
||||||
<div className="bg-gray-100 p-2 rounded text-xs">
|
|
||||||
<strong>DEBUG:</strong> hasExistingInstance = {hasExistingInstance.toString()},
|
|
||||||
status = {existingInstanceData?.status_instancia || 'N/A'},
|
|
||||||
instancia = {existingInstanceData?.instancia_zap || 'N/A'}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Mostra formulário APENAS se NÃO tiver instância conectada */}
|
|
||||||
{!hasExistingInstance && (
|
{!hasExistingInstance && (
|
||||||
<CreateInstanceForm
|
<CreateInstanceForm
|
||||||
onInstanceCreated={handleInstanceCreated}
|
onInstanceCreated={handleInstanceCreated}
|
||||||
@ -177,7 +149,7 @@ const WhatsApp = () => {
|
|||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Mensagem informativa quando já possui instância conectada */}
|
{/* Mensagem quando já tem instância conectada */}
|
||||||
{hasExistingInstance && existingInstanceData && (
|
{hasExistingInstance && existingInstanceData && (
|
||||||
<div className="bg-green-50 border border-green-200 rounded-lg p-4">
|
<div className="bg-green-50 border border-green-200 rounded-lg p-4">
|
||||||
<div className="flex items-center">
|
<div className="flex items-center">
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user