Fix: Check QR code generation

Investigate and address potential issues with QR code generation for WhatsApp connections.
This commit is contained in:
gpt-engineer-app[bot] 2025-05-20 19:49:35 +00:00
parent 03bb67872a
commit c461f132fb
3 changed files with 55 additions and 24 deletions

View File

@ -1,5 +1,5 @@
import { useState } from 'react'; import { useState, useEffect } from 'react';
import { import {
Dialog, Dialog,
DialogContent, DialogContent,
@ -9,7 +9,7 @@ import {
} from '@/components/ui/dialog'; } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { Alert, AlertDescription } from '@/components/ui/alert'; import { Alert, AlertDescription } from '@/components/ui/alert';
import { RefreshCw } from 'lucide-react'; import { RefreshCw, ScanQrCode } from 'lucide-react';
import { WhatsAppInstance } from '@/types/whatsAppTypes'; import { WhatsAppInstance } from '@/types/whatsAppTypes';
import { fetchQrCode } from '@/services/whatsAppService'; import { fetchQrCode } from '@/services/whatsAppService';
import { useToast } from '@/hooks/use-toast'; import { useToast } from '@/hooks/use-toast';
@ -32,6 +32,17 @@ const QrCodeDialog = ({
const [qrCodeData, setQrCodeData] = useState<string | null>(null); const [qrCodeData, setQrCodeData] = useState<string | null>(null);
const [qrError, setQrError] = useState<string | null>(null); const [qrError, setQrError] = useState<string | null>(null);
// Auto-fetch QR code when dialog opens with an active instance
useEffect(() => {
if (open && activeInstance) {
handleRefreshQrCode();
} else {
// Clear QR code data when dialog closes
setQrCodeData(null);
setQrError(null);
}
}, [open, activeInstance]);
const handleOpenChange = (newOpen: boolean) => { const handleOpenChange = (newOpen: boolean) => {
onOpenChange(newOpen); onOpenChange(newOpen);
@ -55,11 +66,14 @@ const QrCodeDialog = ({
if (data && data.base64) { if (data && data.base64) {
// Save the base64 image data directly - it already contains the data:image prefix // Save the base64 image data directly - it already contains the data:image prefix
setQrCodeData(data.base64); setQrCodeData(data.base64);
setQrError(null);
} else { } else {
setQrCodeData(null);
setQrError("QR Code não disponível. A instância pode já estar conectada ou houve um erro na API."); setQrError("QR Code não disponível. A instância pode já estar conectada ou houve um erro na API.");
} }
} catch (error) { } catch (error) {
console.error("Error fetching QR code:", error); console.error("Error fetching QR code:", error);
setQrCodeData(null);
setQrError("Falha ao obter QR Code. Verifique a conexão ou tente novamente mais tarde."); setQrError("Falha ao obter QR Code. Verifique a conexão ou tente novamente mais tarde.");
toast({ toast({
title: "Erro ao obter QR Code", title: "Erro ao obter QR Code",
@ -82,7 +96,8 @@ const QrCodeDialog = ({
</DialogHeader> </DialogHeader>
<div className="flex flex-col items-center space-y-4 py-4"> <div className="flex flex-col items-center space-y-4 py-4">
{loadingQR && ( {loadingQR && (
<div className="text-center py-8"> <div className="text-center py-8 flex flex-col items-center">
<RefreshCw className="h-8 w-8 animate-spin mb-2 text-gray-500" />
<p>Carregando QR Code...</p> <p>Carregando QR Code...</p>
</div> </div>
)} )}
@ -90,15 +105,20 @@ const QrCodeDialog = ({
{qrCodeData && !loadingQR && ( {qrCodeData && !loadingQR && (
<div className="flex flex-col items-center space-y-4"> <div className="flex flex-col items-center space-y-4">
<div className="border p-4 bg-white rounded-md"> <div className="border p-4 bg-white rounded-md">
<img {qrCodeData.startsWith('data:image/') ? (
src={qrCodeData} <img
alt="QR Code WhatsApp" src={qrCodeData}
className="w-full h-auto max-w-[250px]" alt="QR Code WhatsApp"
/> className="w-full h-auto max-w-[250px]"
/>
) : (
<div className="text-center text-red-500">Formato de QR Code inválido</div>
)}
</div>
<div className="flex items-center gap-2 text-sm text-center text-gray-600">
<ScanQrCode className="h-4 w-4" />
<p>Escaneie este QR Code com seu WhatsApp para finalizar a conexão</p>
</div> </div>
<p className="text-sm text-center">
Escaneie este QR Code com seu WhatsApp para finalizar a conexão.
</p>
</div> </div>
)} )}
@ -116,8 +136,8 @@ const QrCodeDialog = ({
disabled={loadingQR} disabled={loadingQR}
className="flex items-center" className="flex items-center"
> >
<RefreshCw className="h-4 w-4 mr-2" /> <RefreshCw className={`h-4 w-4 mr-2 ${loadingQR ? 'animate-spin' : ''}`} />
Atualizar QR Code {loadingQR ? 'Atualizando...' : 'Atualizar QR Code'}
</Button> </Button>
)} )}
<Button variant="ghost" onClick={() => onOpenChange(false)}> <Button variant="ghost" onClick={() => onOpenChange(false)}>

View File

@ -154,14 +154,15 @@ export const useWhatsAppActions = (
// Handler for when QR code dialog is requested // Handler for when QR code dialog is requested
const handleViewQrCode = async (instance: WhatsAppInstance) => { const handleViewQrCode = async (instance: WhatsAppInstance) => {
console.log(`Opening QR code dialog for instance: ${instance.instanceName}`); console.log(`Opening QR code dialog for instance: ${instance.instanceName}`);
// First set the active instance and open dialog to show loading state
setActiveInstance(instance); setActiveInstance(instance);
setQrDialogOpen(true); setQrDialogOpen(true);
try { try {
const data = await fetchQrCode(instance.instanceName); // Pre-fetch QR code data - this will be handled by the dialog itself now
console.log('QR Code API response:', data); // with the useEffect in the dialog component
console.log('QR Code dialog opened, fetching will be handled by dialog component');
// If the fetchQrCode call was successful, QrCodeDialog will handle showing the QR code
} catch (error) { } catch (error) {
console.error("Error initiating QR code fetch:", error); console.error("Error initiating QR code fetch:", error);
toast({ toast({
@ -169,7 +170,6 @@ export const useWhatsAppActions = (
description: "Falha ao iniciar obtenção de QR Code. Tente novamente.", description: "Falha ao iniciar obtenção de QR Code. Tente novamente.",
variant: "destructive", variant: "destructive",
}); });
setQrDialogOpen(false);
} }
}; };

View File

@ -32,12 +32,23 @@ export const createWhatsAppInstance = async (
* Fetches QR code for an instance * Fetches QR code for an instance
*/ */
export const fetchQrCode = async (instanceName: string): Promise<any> => { export const fetchQrCode = async (instanceName: string): Promise<any> => {
console.log(`Fetching QR code for instance: ${instanceName}`); try {
console.log(`Fetching QR code for instance: ${instanceName}`);
const data = await makeRequest(`/instance/connect/${encodeURIComponent(instanceName)}`, 'GET');
const data = await makeRequest(`/instance/connect/${encodeURIComponent(instanceName)}`, 'GET');
console.log('QR code fetch response:', data);
return data; console.log('QR code fetch response:', data);
// Verify that the QR code exists in the response
if (!data || !data.base64) {
console.warn('QR code response missing base64 data:', data);
}
return data;
} catch (error) {
console.error(`Error fetching QR code for ${instanceName}:`, error);
throw error;
}
}; };
/** /**