diff --git a/src/components/whatsapp/QrCodeDialog.tsx b/src/components/whatsapp/QrCodeDialog.tsx index 2011827..59d8810 100644 --- a/src/components/whatsapp/QrCodeDialog.tsx +++ b/src/components/whatsapp/QrCodeDialog.tsx @@ -11,8 +11,9 @@ import { Button } from '@/components/ui/button'; import { Alert, AlertDescription } from '@/components/ui/alert'; import { RefreshCw, ScanQrCode } from 'lucide-react'; import { WhatsAppInstance } from '@/types/whatsAppTypes'; -import { fetchQrCode } from '@/services/whatsAppService'; +import { fetchQrCode, fetchConnectionState } from '@/services/whatsAppService'; import { useToast } from '@/hooks/use-toast'; +import { useWebhookConnection } from '@/hooks/whatsApp/useWebhookConnection'; interface QrCodeDialogProps { open: boolean; @@ -28,26 +29,86 @@ const QrCodeDialog = ({ onStatusCheck }: QrCodeDialogProps) => { const { toast } = useToast(); + const { setupWebhookAfterConnection } = useWebhookConnection(); const [loadingQR, setLoadingQR] = useState(false); const [qrCodeData, setQrCodeData] = useState(null); const [qrError, setQrError] = useState(null); + const [isCheckingConnection, setIsCheckingConnection] = useState(false); + const [connectionCheckInterval, setConnectionCheckInterval] = useState(null); // Auto-fetch QR code when dialog opens with an active instance useEffect(() => { if (open && activeInstance) { handleRefreshQrCode(); + startConnectionCheck(); } else { // Clear QR code data when dialog closes setQrCodeData(null); setQrError(null); + stopConnectionCheck(); } + + return () => { + stopConnectionCheck(); + }; }, [open, activeInstance]); + const startConnectionCheck = () => { + if (!activeInstance) return; + + console.log('Iniciando verificação periódica de conexão...'); + setIsCheckingConnection(true); + + const interval = setInterval(async () => { + try { + const connectionState = await fetchConnectionState(activeInstance.instanceName); + console.log(`Estado da conexão para ${activeInstance.instanceName}:`, connectionState); + + if (connectionState === 'open') { + console.log('🎉 Conexão estabelecida com sucesso!'); + + // Parar a verificação + stopConnectionCheck(); + + // Configurar webhook + const userEmail = localStorage.getItem('userEmail'); + if (userEmail) { + await setupWebhookAfterConnection(userEmail); + } + + // Mostrar sucesso + toast({ + title: "WhatsApp Conectado!", + description: "Conexão estabelecida com sucesso. Webhook configurado automaticamente.", + }); + + // Fechar o dialog e atualizar status + onOpenChange(false); + onStatusCheck(); + } + } catch (error) { + console.error('Erro ao verificar estado da conexão:', error); + } + }, 3000); // Verifica a cada 3 segundos + + setConnectionCheckInterval(interval); + }; + + const stopConnectionCheck = () => { + if (connectionCheckInterval) { + console.log('Parando verificação de conexão...'); + clearInterval(connectionCheckInterval); + setConnectionCheckInterval(null); + setIsCheckingConnection(false); + } + }; + const handleOpenChange = (newOpen: boolean) => { onOpenChange(newOpen); // After dialog closes, trigger status check to update connection state if (!newOpen) { + stopConnectionCheck(); onStatusCheck(); } }; @@ -67,6 +128,11 @@ const QrCodeDialog = ({ // Save the base64 image data directly - it already contains the data:image prefix setQrCodeData(data.base64); setQrError(null); + + // Iniciar verificação de conexão quando QR code é exibido + if (!isCheckingConnection) { + startConnectionCheck(); + } } else { setQrCodeData(null); setQrError("QR Code não disponível. A instância pode já estar conectada ou houve um erro na API."); @@ -92,6 +158,11 @@ const QrCodeDialog = ({ Conectar WhatsApp - {activeInstance?.instanceName} Escaneie o QR Code com seu WhatsApp para finalizar a conexão + {isCheckingConnection && ( + + ⏳ Aguardando conexão... (verificando automaticamente) + + )}
@@ -119,6 +190,14 @@ const QrCodeDialog = ({

Escaneie este QR Code com seu WhatsApp para finalizar a conexão

+ {isCheckingConnection && ( +
+
+ + Verificando conexão automaticamente... +
+
+ )} )} diff --git a/src/hooks/whatsApp/useWebhookConnection.ts b/src/hooks/whatsApp/useWebhookConnection.ts new file mode 100644 index 0000000..f2b3040 --- /dev/null +++ b/src/hooks/whatsApp/useWebhookConnection.ts @@ -0,0 +1,35 @@ + +import { useToast } from '@/hooks/use-toast'; +import { createEvolutionWebhook } from '@/services/whatsApp/webhookService'; + +export const useWebhookConnection = () => { + const { toast } = useToast(); + + const setupWebhookAfterConnection = async (userEmail: string) => { + try { + console.log('🔗 Configurando webhook após conexão bem-sucedida...'); + + await createEvolutionWebhook(userEmail); + + console.log('✅ Webhook configurado com sucesso'); + + toast({ + title: "Webhook Configurado", + description: "Webhook foi configurado automaticamente para receber mensagens.", + }); + + } catch (error) { + console.error('❌ Erro ao configurar webhook:', error); + + toast({ + title: "Aviso: Webhook", + description: "WhatsApp conectado, mas houve falha na configuração do webhook.", + variant: "destructive", + }); + } + }; + + return { + setupWebhookAfterConnection + }; +}; diff --git a/src/services/whatsApp/index.ts b/src/services/whatsApp/index.ts index d49148e..338965e 100644 --- a/src/services/whatsApp/index.ts +++ b/src/services/whatsApp/index.ts @@ -3,6 +3,8 @@ export * from './instanceManagement'; export * from './instanceActions'; export * from './localStorage'; +export * from './webhookService'; // Import and re-export the disconnect function specifically export { disconnectInstance } from './instanceActions'; +export { createEvolutionWebhook } from './webhookService'; diff --git a/src/services/whatsApp/webhookService.ts b/src/services/whatsApp/webhookService.ts new file mode 100644 index 0000000..adbab1d --- /dev/null +++ b/src/services/whatsApp/webhookService.ts @@ -0,0 +1,45 @@ + +import { makeRequest } from './apiHelpers'; + +/** + * Cria um webhook na Evolution API para o usuário + */ +export const createEvolutionWebhook = async (userEmail: string): Promise => { + try { + console.log(`Criando webhook para o usuário: ${userEmail}`); + + // URL do endpoint - mantém o @ normal no email + const endpoint = `/webhook/set/${userEmail}`; + + // No body, troca @ por _ no email + const emailWithUnderscore = userEmail.replace('@', '_'); + + const webhookBody = { + webhook: { + enabled: true, + url: `https://webhookn8n.innova1001.com.br/webhook/${emailWithUnderscore}`, + webhookByEvents: true, + webhookBase64: true, + events: [ + "MESSAGES_UPSERT" + ] + } + }; + + console.log('Dados do webhook:', { + endpoint, + emailOriginal: userEmail, + emailComUnderscore: emailWithUnderscore, + webhookUrl: webhookBody.webhook.url + }); + + const response = await makeRequest(endpoint, 'POST', webhookBody); + + console.log(`✅ Webhook criado com sucesso para ${userEmail}:`, response); + return response; + + } catch (error) { + console.error(`❌ Erro ao criar webhook for ${userEmail}:`, error); + throw error; + } +}; diff --git a/src/services/whatsAppService.ts b/src/services/whatsAppService.ts index 0eba534..cf2cdf3 100644 --- a/src/services/whatsAppService.ts +++ b/src/services/whatsAppService.ts @@ -5,6 +5,7 @@ export * from './whatsApp/instanceManagement'; export * from './whatsApp/instanceActions'; export * from './whatsApp/localStorage'; +export * from './whatsApp/webhookService'; // Export config values if needed by other parts of the app export { SERVER_URL, API_KEY, STORAGE_KEY } from './whatsApp/config';