diff --git a/src/pages/WhatsApp.tsx b/src/pages/WhatsApp.tsx index 802d324..0e4226c 100644 --- a/src/pages/WhatsApp.tsx +++ b/src/pages/WhatsApp.tsx @@ -1,17 +1,19 @@ -import { useState } from 'react'; +import { useState, useEffect } from 'react'; import Layout from '@/components/layout/Layout'; -import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; +import { Card, CardContent, CardDescription, CardHeader, CardTitle, CardFooter } from '@/components/ui/card'; import { Input } from '@/components/ui/input'; import { Button } from '@/components/ui/button'; import { useToast } from '@/hooks/use-toast'; import { Label } from '@/components/ui/label'; -import { MessageCircle, QrCode, RefreshCw } from 'lucide-react'; +import { MessageCircle, QrCode, RefreshCw, Smartphone, Eye } from 'lucide-react'; import { Alert, AlertDescription } from '@/components/ui/alert'; +import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '@/components/ui/dialog'; interface WhatsAppInstance { instanceName: string; - instanceId?: string; + instanceId: string; + phoneNumber: string; status?: string; qrcode?: string; } @@ -26,21 +28,30 @@ const WhatsApp = () => { return userName; }); const [phoneNumber, setPhoneNumber] = useState(''); - const [instance, setInstance] = useState(() => { - // Check if we have a stored instance - const storedInstanceId = localStorage.getItem('whatsappInstanceId'); - const storedInstanceName = localStorage.getItem('whatsappInstanceName'); - - if (storedInstanceId && storedInstanceName) { - return { - instanceName: storedInstanceName, - instanceId: storedInstanceId - }; - } - return null; - }); + const [instances, setInstances] = useState([]); + const [activeInstance, setActiveInstance] = useState(null); const [qrCodeData, setQrCodeData] = useState(null); const [qrError, setQrError] = useState(null); + const [qrDialogOpen, setQrDialogOpen] = useState(false); + + // Load saved instances from localStorage on component mount + useEffect(() => { + const savedInstances = localStorage.getItem('whatsappInstances'); + if (savedInstances) { + try { + setInstances(JSON.parse(savedInstances)); + } catch (error) { + console.error("Error parsing saved instances:", error); + } + } + }, []); + + // Save instances to localStorage whenever they change + useEffect(() => { + if (instances.length > 0) { + localStorage.setItem('whatsappInstances', JSON.stringify(instances)); + } + }, [instances]); const createInstance = async () => { // Validate form fields @@ -89,28 +100,32 @@ const WhatsApp = () => { throw new Error(data.message || 'Erro ao criar instância'); } - // Handle successful response - const newInstance = { + // Create new instance object + const newInstance: WhatsAppInstance = { instanceName, instanceId: data.instanceId, + phoneNumber, status: data.status, qrcode: data.qrcode }; - setInstance(newInstance); - - // Save the instance details for later use - localStorage.setItem('whatsappInstanceId', data.instanceId); - localStorage.setItem('whatsappInstanceName', instanceName); + // Add new instance to the list + setInstances(prevInstances => [...prevInstances, newInstance]); toast({ title: "Sucesso!", description: "Instância do WhatsApp criada com sucesso!" }); - // If there's a QR code in the response, set it + // Reset form fields + setInstanceName(localStorage.getItem('userName') || ''); + setPhoneNumber(''); + + // If there's a QR code in the response, show it if (data.qrcode) { + setActiveInstance(newInstance); setQrCodeData(data.qrcode); + setQrDialogOpen(true); } } catch (error) { console.error("Error creating WhatsApp instance:", error); @@ -119,24 +134,16 @@ const WhatsApp = () => { description: "Ocorreu um erro ao conectar com a API. Tente novamente mais tarde.", variant: "destructive", }); - setQrError("Falha ao obter QR Code. Tente novamente."); } finally { setLoading(false); } }; - const fetchQrCode = async () => { - if (!instance?.instanceId) { - toast({ - title: "Erro", - description: "Nenhuma instância disponível. Crie uma instância primeiro.", - variant: "destructive", - }); - return; - } - + const fetchQrCode = async (instance: WhatsAppInstance) => { + setActiveInstance(instance); setLoadingQR(true); setQrError(null); + setQrDialogOpen(true); try { const serverUrl = "evolutionapi2.innova1001.com.br"; @@ -174,6 +181,22 @@ const WhatsApp = () => { } }; + const deleteInstance = (instanceId: string) => { + setInstances(prevInstances => prevInstances.filter(instance => instance.instanceId !== instanceId)); + // If we're viewing QR code for this instance, close the dialog + if (activeInstance?.instanceId === instanceId) { + setQrDialogOpen(false); + } + // Update localStorage + const updatedInstances = instances.filter(instance => instance.instanceId !== instanceId); + localStorage.setItem('whatsappInstances', JSON.stringify(updatedInstances)); + + toast({ + title: "Instância removida", + description: "A instância do WhatsApp foi removida com sucesso.", + }); + }; + return (
@@ -181,85 +204,118 @@ const WhatsApp = () => {

Conectar WhatsApp

- {!instance?.instanceId ? ( - - -
- - Vincular WhatsApp ao App -
- - Preencha os campos abaixo para conectar sua conta WhatsApp - -
- -
- - setInstanceName(e.target.value)} - placeholder="Digite um nome para a instância" - required - /> -

O nome será usado para identificar esta conexão

-
- -
- - setPhoneNumber(e.target.value)} - placeholder="559999999999" - required - /> -

Digite o número com DDD e código do país

-
- - -
-
- ) : ( - - -
- - WhatsApp - {instance.instanceName} -
- + {/* Form to create a new instance */} + + +
+ + Vincular WhatsApp ao App +
+ + Preencha os campos abaixo para conectar sua conta WhatsApp + +
+ +
+ + setInstanceName(e.target.value)} + placeholder="Digite um nome para a instância" + required + /> +

O nome será usado para identificar esta conexão

+
+ +
+ + setPhoneNumber(e.target.value)} + placeholder="559999999999" + required + /> +

Digite o número com DDD e código do país

+
+ + +
+
+ + {/* List of created instances */} + {instances.length > 0 && ( +
+

Instâncias Criadas

+
+ {instances.map((instance) => ( + + + {instance.instanceName} + + +
+
+ + {instance.phoneNumber} +
+ {instance.status && ( +
+ + Status: {instance.status} +
+ )} +
+
+ + + + +
+ ))} +
+
+ )} + + {/* QR Code Dialog */} + + + + Conectar WhatsApp - {activeInstance?.instanceName} + Escaneie o QR Code com seu WhatsApp para finalizar a conexão -
-
- -
-

Instância criada com sucesso!

-

ID da instância: {instance.instanceId}

-
- - {!qrCodeData && !qrError && !loadingQR && ( - - )} - + + +
{loadingQR && (

Carregando QR Code...

)} - {qrCodeData && ( + {qrCodeData && !loadingQR && (
{

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

-
)} - {qrError && ( -
- - {qrError} - - -
+ {qrError && !loadingQR && ( + + {qrError} + )} - - - )} + +
+ {activeInstance && ( + + )} + +
+
+ +
);