From a9ee70ccb6abf64136e2c1861ed2f8f8ea5aea6e Mon Sep 17 00:00:00 2001 From: "gpt-engineer-app[bot]" <159125892+gpt-engineer-app[bot]@users.noreply.github.com> Date: Tue, 20 May 2025 19:26:10 +0000 Subject: [PATCH] feat: Implement "Atualizar Lista" button The "Connect WhatsApp" menu now loads instances only on clicking the "Atualizar Lista" button. The button fetches instances from the API, filters by the user's instance name, and displays the results. It also shows an appropriate message if no instances are found and addresses potential rendering errors. --- src/components/whatsapp/InstanceList.tsx | 26 +++++---- src/hooks/whatsApp/useInstanceRefresh.ts | 64 +++++++++++---------- src/hooks/whatsApp/useWhatsAppInstance.ts | 7 +-- src/pages/WhatsApp.tsx | 28 ++++++--- src/services/whatsApp/instanceManagement.ts | 3 +- 5 files changed, 73 insertions(+), 55 deletions(-) diff --git a/src/components/whatsapp/InstanceList.tsx b/src/components/whatsapp/InstanceList.tsx index 21eedf1..b18ccd8 100644 --- a/src/components/whatsapp/InstanceList.tsx +++ b/src/components/whatsapp/InstanceList.tsx @@ -26,13 +26,26 @@ const InstanceList = ({ onRefreshInstances, isRefreshing }: InstanceListProps) => { - if (instances.length === 0) { + // Safely check if instances is an array and has elements + const hasInstances = Array.isArray(instances) && instances.length > 0; + + if (!hasInstances) { return (

Nenhuma instância criada ainda.

-

Crie uma instância usando o formulário acima.

+

Clique em 'Atualizar Lista' para buscar novamente.

+
@@ -43,15 +56,6 @@ const InstanceList = ({

Instâncias Criadas

-
{instances.map((instance) => ( diff --git a/src/hooks/whatsApp/useInstanceRefresh.ts b/src/hooks/whatsApp/useInstanceRefresh.ts index 6554006..acbc067 100644 --- a/src/hooks/whatsApp/useInstanceRefresh.ts +++ b/src/hooks/whatsApp/useInstanceRefresh.ts @@ -28,9 +28,18 @@ export const useInstanceRefresh = ( const response = await fetchAllInstances(); console.log("Fetched instances from server:", response); - if (response.instances && Array.isArray(response.instances)) { + if (response && response.instances && Array.isArray(response.instances)) { + // Busca o nome da instância salvo para o usuário atual + const savedInstanceName = localStorage.getItem(`whatsapp_instance_name_${currentUserId}`); + console.log("Saved instance name for current user:", savedInstanceName); + + // Filtra as instâncias pelo nome criado pelo usuário + const filteredInstances = savedInstanceName + ? response.instances.filter(instance => instance.instanceName === savedInstanceName) + : response.instances; + // Mapeia as instâncias do servidor para o formato correto com userId - const serverInstances: WhatsAppInstance[] = response.instances + const serverInstances: WhatsAppInstance[] = filteredInstances .map(serverInstance => { // Ensure we convert server state to valid connectionState let connectionState: 'open' | 'closed' | 'connecting'; @@ -53,36 +62,28 @@ export const useInstanceRefresh = ( }; }); - console.log("Mapped server instances:", serverInstances); + console.log("Filtered server instances for this user:", serverInstances); - // Identifica instâncias novas que não existem localmente - const localInstanceIds = new Set(instances.map(i => i.instanceId)); - const newServerInstances = serverInstances.filter(i => !localInstanceIds.has(i.instanceId)); - - // Atualiza instâncias existentes com dados do servidor - const updatedExistingInstances = instances.map(localInstance => { - const serverMatch = serverInstances.find(si => si.instanceId === localInstance.instanceId); - if (serverMatch) { - return { - ...localInstance, - connectionState: serverMatch.connectionState, - status: serverMatch.status - }; - } - return localInstance; - }); - - // Combina tudo - const allInstances = [...updatedExistingInstances, ...newServerInstances]; - - console.log("Combined instances after refresh:", allInstances); - setInstances(allInstances); - - toast({ - title: "Sucesso", - description: `${serverInstances.length} instâncias encontradas no servidor`, - }); + if (serverInstances.length > 0) { + setInstances(serverInstances); + + toast({ + title: "Sucesso", + description: `${serverInstances.length} instância(s) encontrada(s) para este usuário`, + }); + } else { + // Clear instances if none found for this user + setInstances([]); + + toast({ + title: "Aviso", + description: "Nenhuma instância encontrada para este usuário", + }); + } } else { + // Handle empty or invalid response + setInstances([]); + toast({ title: "Aviso", description: "Nenhuma instância encontrada no servidor", @@ -90,6 +91,9 @@ export const useInstanceRefresh = ( } } catch (error) { console.error("Erro ao buscar instâncias:", error); + // Ensure we don't leave instances in an undefined state + setInstances([]); + toast({ title: "Erro", description: "Falha ao buscar instâncias do servidor", diff --git a/src/hooks/whatsApp/useWhatsAppInstance.ts b/src/hooks/whatsApp/useWhatsAppInstance.ts index 4b7b5bb..d76e3cc 100644 --- a/src/hooks/whatsApp/useWhatsAppInstance.ts +++ b/src/hooks/whatsApp/useWhatsAppInstance.ts @@ -117,12 +117,7 @@ export const useWhatsAppInstance = ( } }; - // Run once when component mounts or currentUserId changes - useEffect(() => { - if (instanceName && currentUserId) { - fetchInstanceByName(); - } - }, [currentUserId]); // Only depend on userId changes + // Don't automatically load the instance - removed the useEffect that called fetchInstanceByName return { instanceName, diff --git a/src/pages/WhatsApp.tsx b/src/pages/WhatsApp.tsx index bfc2346..09dd6b5 100644 --- a/src/pages/WhatsApp.tsx +++ b/src/pages/WhatsApp.tsx @@ -10,6 +10,8 @@ import { useWhatsAppInstances } from '@/hooks/useWhatsAppInstances'; import { useWhatsAppActions } from '@/hooks/useWhatsAppActions'; import { useWhatsAppInstance, WHATSAPP_INSTANCE_KEY } from '@/hooks/whatsApp/useWhatsAppInstance'; import { usePeriodicStatusCheck } from '@/hooks/whatsApp/usePeriodicStatusCheck'; +import { Button } from '@/components/ui/button'; +import { RefreshCw } from 'lucide-react'; const WhatsApp = () => { const { @@ -40,11 +42,12 @@ const WhatsApp = () => { isLoading, instanceFound, setInstanceFound, + fetchInstanceByName, saveInstanceName, clearInstanceName } = useWhatsAppInstance(currentUserId, addInstance); - // Set up periodic status checking + // Set up periodic status checking only after instances are loaded usePeriodicStatusCheck(instances.length, checkAllInstancesStatus); // Handler para quando o usuário cria uma nova instância @@ -87,29 +90,40 @@ const WhatsApp = () => { } }; - console.log('Current instances in WhatsApp component:', instances); - console.log('Instance found status:', instanceFound); + // Check if we have any instances to show + const hasInstances = Array.isArray(instances) && instances.length > 0; return (

Conectar WhatsApp

+ + {/* Update List Button - Always visible */} +
{isLoading ? ( - ) : !instanceFound ? ( - // Show create form if no instance found + ) : !instanceFound && !hasInstances ? ( + // Show create form if no instance found and no instances loaded ) : ( - // Only show stats and instance list if instance found + // Only show stats and instance list if instances are available <> {/* Stats component */} - + {hasInstances && } {/* List of created instances */} => { try { console.log('Fetching all instances'); - const data = await makeRequest('/fetch-instances', 'GET'); + // Using the /instance/fetchInstances endpoint as specified in the requirements + const data = await makeRequest('/instance/fetchInstances', 'GET'); console.log('All instances response:', data); return data;