Refactor: Split WhatsApp page into components
Split the WhatsApp page into smaller, reusable components to improve code organization and readability.
This commit is contained in:
parent
a9769b76db
commit
e41618415d
33
src/components/whatsapp/ConnectedInstanceMessage.tsx
Normal file
33
src/components/whatsapp/ConnectedInstanceMessage.tsx
Normal file
@ -0,0 +1,33 @@
|
|||||||
|
|
||||||
|
interface ConnectedInstanceMessageProps {
|
||||||
|
instanceData: {
|
||||||
|
instancia_zap: string;
|
||||||
|
status_instancia: string;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const ConnectedInstanceMessage = ({ instanceData }: ConnectedInstanceMessageProps) => {
|
||||||
|
return (
|
||||||
|
<div className="bg-green-50 border border-green-200 rounded-lg p-4">
|
||||||
|
<div className="flex items-center">
|
||||||
|
<div className="flex-shrink-0">
|
||||||
|
<svg className="h-5 w-5 text-green-400" viewBox="0 0 20 20" fill="currentColor">
|
||||||
|
<path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clipRule="evenodd" />
|
||||||
|
</svg>
|
||||||
|
</div>
|
||||||
|
<div className="ml-3">
|
||||||
|
<h3 className="text-sm font-medium text-green-800">
|
||||||
|
WhatsApp Conectado ✅
|
||||||
|
</h3>
|
||||||
|
<div className="mt-2 text-sm text-green-700">
|
||||||
|
<p>Você já possui uma instância do WhatsApp conectada: <strong>{instanceData.instancia_zap}</strong></p>
|
||||||
|
<p>Status: <strong>{instanceData.status_instancia}</strong></p>
|
||||||
|
<p>Agora você pode criar grupos WhatsApp!</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default ConnectedInstanceMessage;
|
||||||
36
src/components/whatsapp/WhatsAppHeader.tsx
Normal file
36
src/components/whatsapp/WhatsAppHeader.tsx
Normal file
@ -0,0 +1,36 @@
|
|||||||
|
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { RefreshCw } from 'lucide-react';
|
||||||
|
|
||||||
|
interface WhatsAppHeaderProps {
|
||||||
|
userEmail: string;
|
||||||
|
onRefresh: () => void;
|
||||||
|
isRefreshing: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
const WhatsAppHeader = ({ userEmail, onRefresh, isRefreshing }: WhatsAppHeaderProps) => {
|
||||||
|
return (
|
||||||
|
<div className="flex justify-between items-center">
|
||||||
|
<div>
|
||||||
|
<h1 className="text-2xl font-bold tracking-tight">Conectar WhatsApp</h1>
|
||||||
|
{userEmail && (
|
||||||
|
<p className="text-sm text-muted-foreground mt-1">
|
||||||
|
Mostrando instâncias para: <strong>{userEmail}</strong>
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
onClick={onRefresh}
|
||||||
|
disabled={isRefreshing}
|
||||||
|
className="flex items-center gap-2"
|
||||||
|
>
|
||||||
|
<RefreshCw className={`h-4 w-4 ${isRefreshing ? 'animate-spin' : ''}`} />
|
||||||
|
Atualizar
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default WhatsAppHeader;
|
||||||
84
src/components/whatsapp/WhatsAppManager.tsx
Normal file
84
src/components/whatsapp/WhatsAppManager.tsx
Normal file
@ -0,0 +1,84 @@
|
|||||||
|
|
||||||
|
import { WhatsAppInstance } from '@/types/whatsAppTypes';
|
||||||
|
import CreateInstanceForm from '@/components/whatsapp/CreateInstanceForm';
|
||||||
|
import InstanceList from '@/components/whatsapp/InstanceList';
|
||||||
|
import InstanceStats from '@/components/whatsapp/InstanceStats';
|
||||||
|
import QrCodeDialog from '@/components/whatsapp/QrCodeDialog';
|
||||||
|
import ConnectedInstanceMessage from './ConnectedInstanceMessage';
|
||||||
|
|
||||||
|
interface WhatsAppManagerProps {
|
||||||
|
hasExistingInstance: boolean;
|
||||||
|
existingInstanceData: any;
|
||||||
|
instances: WhatsAppInstance[];
|
||||||
|
isRefreshing: boolean;
|
||||||
|
activeInstance: WhatsAppInstance | null;
|
||||||
|
qrDialogOpen: boolean;
|
||||||
|
onInstanceCreated: (instance: WhatsAppInstance) => void;
|
||||||
|
onViewQrCode: (instance: WhatsAppInstance) => void;
|
||||||
|
onDelete: (instanceId: string) => void;
|
||||||
|
onRestart: (instance: WhatsAppInstance) => Promise<void>;
|
||||||
|
onLogout: (instance: WhatsAppInstance) => Promise<void>;
|
||||||
|
onDisconnect: (instance: WhatsAppInstance) => Promise<void>;
|
||||||
|
onSetPresence: (instance: WhatsAppInstance, presence: 'online' | 'offline') => Promise<void>;
|
||||||
|
onRefreshInstances: () => void;
|
||||||
|
onStatusCheck: () => Promise<void>;
|
||||||
|
setQrDialogOpen: (open: boolean) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
const WhatsAppManager = ({
|
||||||
|
hasExistingInstance,
|
||||||
|
existingInstanceData,
|
||||||
|
instances,
|
||||||
|
isRefreshing,
|
||||||
|
activeInstance,
|
||||||
|
qrDialogOpen,
|
||||||
|
onInstanceCreated,
|
||||||
|
onViewQrCode,
|
||||||
|
onDelete,
|
||||||
|
onRestart,
|
||||||
|
onLogout,
|
||||||
|
onDisconnect,
|
||||||
|
onSetPresence,
|
||||||
|
onRefreshInstances,
|
||||||
|
onStatusCheck,
|
||||||
|
setQrDialogOpen
|
||||||
|
}: WhatsAppManagerProps) => {
|
||||||
|
const hasInstances = Array.isArray(instances) && instances.length > 0;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{/* Formulário de criação - APENAS se NÃO tiver instância conectada */}
|
||||||
|
{!hasExistingInstance && (
|
||||||
|
<CreateInstanceForm onInstanceCreated={onInstanceCreated} />
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Mensagem quando já tem instância conectada */}
|
||||||
|
{hasExistingInstance && existingInstanceData && (
|
||||||
|
<ConnectedInstanceMessage instanceData={existingInstanceData} />
|
||||||
|
)}
|
||||||
|
|
||||||
|
{hasInstances && <InstanceStats instances={instances} />}
|
||||||
|
|
||||||
|
<InstanceList
|
||||||
|
instances={instances}
|
||||||
|
onViewQrCode={onViewQrCode}
|
||||||
|
onDelete={onDelete}
|
||||||
|
onRestart={onRestart}
|
||||||
|
onLogout={onLogout}
|
||||||
|
onDisconnect={onDisconnect}
|
||||||
|
onSetPresence={onSetPresence}
|
||||||
|
onRefreshInstances={onRefreshInstances}
|
||||||
|
isRefreshing={isRefreshing}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<QrCodeDialog
|
||||||
|
open={qrDialogOpen}
|
||||||
|
onOpenChange={setQrDialogOpen}
|
||||||
|
activeInstance={activeInstance}
|
||||||
|
onStatusCheck={onStatusCheck}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default WhatsAppManager;
|
||||||
@ -1,83 +0,0 @@
|
|||||||
|
|
||||||
import { useState, useEffect } from 'react';
|
|
||||||
import { getUserWhatsAppInstance } from '@/services/whatsAppInstanceService';
|
|
||||||
|
|
||||||
interface WhatsAppInstanceData {
|
|
||||||
instancia_zap: string | null;
|
|
||||||
status_instancia: string | null;
|
|
||||||
whatsapp: string | null;
|
|
||||||
}
|
|
||||||
|
|
||||||
export const useWhatsAppInstanceVerification = (userEmail: string) => {
|
|
||||||
const [hasWhatsAppInstance, setHasWhatsAppInstance] = useState<boolean>(false);
|
|
||||||
const [checkingInstance, setCheckingInstance] = useState<boolean>(true);
|
|
||||||
const [userInstance, setUserInstance] = useState<WhatsAppInstanceData | null>(null);
|
|
||||||
|
|
||||||
const checkUserInstance = async () => {
|
|
||||||
if (!userEmail) {
|
|
||||||
console.log('❌ Email do usuário não fornecido');
|
|
||||||
setCheckingInstance(false);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
setCheckingInstance(true);
|
|
||||||
try {
|
|
||||||
console.log('🔍 [GRUPO] Verificando instância para criação de grupo:', userEmail);
|
|
||||||
|
|
||||||
const instanceData = await getUserWhatsAppInstance(userEmail);
|
|
||||||
console.log('📋 [GRUPO] Dados da instância encontrados:', instanceData);
|
|
||||||
|
|
||||||
if (instanceData) {
|
|
||||||
// Verificação correta: deve ter instancia_zap igual ao email E status conectado
|
|
||||||
const hasValidInstance = !!(
|
|
||||||
instanceData &&
|
|
||||||
instanceData.instancia_zap &&
|
|
||||||
instanceData.instancia_zap.trim() !== '' &&
|
|
||||||
instanceData.instancia_zap !== 'null' &&
|
|
||||||
instanceData.instancia_zap !== null &&
|
|
||||||
instanceData.instancia_zap.toLowerCase() === userEmail.toLowerCase() &&
|
|
||||||
instanceData.status_instancia === 'conectado'
|
|
||||||
);
|
|
||||||
|
|
||||||
console.log('✅ [GRUPO] Instância válida para criar grupos:', hasValidInstance, {
|
|
||||||
instancia_zap: instanceData.instancia_zap,
|
|
||||||
status_instancia: instanceData.status_instancia,
|
|
||||||
userEmail: userEmail,
|
|
||||||
instanceMatchesEmail: instanceData.instancia_zap?.toLowerCase() === userEmail.toLowerCase(),
|
|
||||||
isConnected: instanceData.status_instancia === 'conectado',
|
|
||||||
hasValidInstance
|
|
||||||
});
|
|
||||||
|
|
||||||
setHasWhatsAppInstance(hasValidInstance);
|
|
||||||
setUserInstance(instanceData);
|
|
||||||
} else {
|
|
||||||
console.log('❌ [GRUPO] Nenhuma instância encontrada');
|
|
||||||
setHasWhatsAppInstance(false);
|
|
||||||
setUserInstance(null);
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.error('❌ [GRUPO] Erro ao verificar instância do usuário:', error);
|
|
||||||
setHasWhatsAppInstance(false);
|
|
||||||
setUserInstance(null);
|
|
||||||
} finally {
|
|
||||||
setCheckingInstance(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
checkUserInstance();
|
|
||||||
}, [userEmail]);
|
|
||||||
|
|
||||||
// Função para forçar re-verificação (útil quando o status da instância muda)
|
|
||||||
const recheckInstance = () => {
|
|
||||||
console.log('🔄 [GRUPO] Forçando re-verificação da instância');
|
|
||||||
checkUserInstance();
|
|
||||||
};
|
|
||||||
|
|
||||||
return {
|
|
||||||
hasWhatsAppInstance,
|
|
||||||
checkingInstance,
|
|
||||||
userInstance,
|
|
||||||
recheckInstance
|
|
||||||
};
|
|
||||||
};
|
|
||||||
@ -1,18 +1,14 @@
|
|||||||
|
|
||||||
import { WhatsAppInstance } from '@/types/whatsAppTypes';
|
import { WhatsAppInstance } from '@/types/whatsAppTypes';
|
||||||
import Layout from '@/components/layout/Layout';
|
import Layout from '@/components/layout/Layout';
|
||||||
import CreateInstanceForm from '@/components/whatsapp/CreateInstanceForm';
|
|
||||||
import InstanceList from '@/components/whatsapp/InstanceList';
|
|
||||||
import InstanceStats from '@/components/whatsapp/InstanceStats';
|
|
||||||
import QrCodeDialog from '@/components/whatsapp/QrCodeDialog';
|
|
||||||
import LoadingState from '@/components/whatsapp/LoadingState';
|
import LoadingState from '@/components/whatsapp/LoadingState';
|
||||||
|
import WhatsAppHeader from '@/components/whatsapp/WhatsAppHeader';
|
||||||
|
import WhatsAppManager from '@/components/whatsapp/WhatsAppManager';
|
||||||
import { useWhatsAppInstances } from '@/hooks/useWhatsAppInstances';
|
import { useWhatsAppInstances } from '@/hooks/useWhatsAppInstances';
|
||||||
import { useWhatsAppActions } from '@/hooks/useWhatsAppActions';
|
import { useWhatsAppActions } from '@/hooks/useWhatsAppActions';
|
||||||
import { useWhatsAppInstance, WHATSAPP_INSTANCE_KEY } from '@/hooks/whatsApp/useWhatsAppInstance';
|
import { useWhatsAppInstance, WHATSAPP_INSTANCE_KEY } from '@/hooks/whatsApp/useWhatsAppInstance';
|
||||||
import { usePeriodicStatusCheck } from '@/hooks/whatsApp/usePeriodicStatusCheck';
|
import { usePeriodicStatusCheck } from '@/hooks/whatsApp/usePeriodicStatusCheck';
|
||||||
import { useExistingInstanceCheck } from '@/hooks/whatsapp/useExistingInstanceCheck';
|
import { useExistingInstanceCheck } from '@/hooks/whatsapp/useExistingInstanceCheck';
|
||||||
import { Button } from '@/components/ui/button';
|
|
||||||
import { RefreshCw } from 'lucide-react';
|
|
||||||
|
|
||||||
const WhatsApp = () => {
|
const WhatsApp = () => {
|
||||||
const {
|
const {
|
||||||
@ -50,13 +46,10 @@ const WhatsApp = () => {
|
|||||||
|
|
||||||
const userEmail = (localStorage.getItem('userEmail') || '').toLowerCase();
|
const userEmail = (localStorage.getItem('userEmail') || '').toLowerCase();
|
||||||
|
|
||||||
// Hook UNIFICADO para verificação de instância existente
|
|
||||||
const {
|
const {
|
||||||
hasExistingInstance,
|
hasExistingInstance,
|
||||||
checkingExistingInstance,
|
checkingInstance,
|
||||||
existingInstanceData,
|
instanceData,
|
||||||
setHasExistingInstance,
|
|
||||||
setExistingInstanceData,
|
|
||||||
recheckInstance
|
recheckInstance
|
||||||
} = useExistingInstanceCheck(userEmail);
|
} = useExistingInstanceCheck(userEmail);
|
||||||
|
|
||||||
@ -72,12 +65,10 @@ const WhatsApp = () => {
|
|||||||
handleViewQrCode(newInstance);
|
handleViewQrCode(newInstance);
|
||||||
}
|
}
|
||||||
|
|
||||||
// O mais importante: após criar, chame a função para re-verificar do banco de dados!
|
|
||||||
// Isso garante que o estado seja baseado em dados reais, não em uma suposição.
|
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
recheckInstance();
|
recheckInstance();
|
||||||
checkAllInstancesStatus();
|
checkAllInstancesStatus();
|
||||||
}, 2000); // Um pequeno delay para dar tempo ao backend de atualizar
|
}, 2000);
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleDeleteInstanceWrapper = (instanceId: string) => {
|
const handleDeleteInstanceWrapper = (instanceId: string) => {
|
||||||
@ -88,16 +79,11 @@ const WhatsApp = () => {
|
|||||||
|
|
||||||
if (instanceToDelete.instanceName === instanceName) {
|
if (instanceToDelete.instanceName === instanceName) {
|
||||||
clearInstanceName();
|
clearInstanceName();
|
||||||
setHasExistingInstance(false);
|
|
||||||
setExistingInstanceData(null);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const hasInstances = Array.isArray(instances) && instances.length > 0;
|
if (checkingInstance || isLoading) {
|
||||||
|
|
||||||
// Loading enquanto verifica instância
|
|
||||||
if (checkingExistingInstance || isLoading) {
|
|
||||||
return (
|
return (
|
||||||
<Layout>
|
<Layout>
|
||||||
<LoadingState message="Verificando suas instâncias..." />
|
<LoadingState message="Verificando suas instâncias..." />
|
||||||
@ -108,77 +94,29 @@ const WhatsApp = () => {
|
|||||||
return (
|
return (
|
||||||
<Layout>
|
<Layout>
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
<div className="flex justify-between items-center">
|
<WhatsAppHeader
|
||||||
<div>
|
userEmail={userEmail}
|
||||||
<h1 className="text-2xl font-bold tracking-tight">Conectar WhatsApp</h1>
|
onRefresh={recheckInstance}
|
||||||
{userEmail && (
|
isRefreshing={checkingInstance}
|
||||||
<p className="text-sm text-muted-foreground mt-1">
|
/>
|
||||||
Mostrando instâncias para: <strong>{userEmail}</strong>
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<Button
|
|
||||||
variant="outline"
|
|
||||||
onClick={recheckInstance}
|
|
||||||
disabled={checkingExistingInstance}
|
|
||||||
className="flex items-center gap-2"
|
|
||||||
>
|
|
||||||
<RefreshCw className={`h-4 w-4 ${checkingExistingInstance ? 'animate-spin' : ''}`} />
|
|
||||||
Atualizar
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Formulário de criação - APENAS se NÃO tiver instância conectada */}
|
<WhatsAppManager
|
||||||
{!hasExistingInstance && (
|
hasExistingInstance={hasExistingInstance}
|
||||||
<CreateInstanceForm
|
existingInstanceData={instanceData}
|
||||||
onInstanceCreated={handleInstanceCreated}
|
instances={instances}
|
||||||
initialInstanceName={instanceName}
|
isRefreshing={isRefreshing}
|
||||||
/>
|
activeInstance={activeInstance}
|
||||||
)}
|
qrDialogOpen={qrDialogOpen}
|
||||||
|
onInstanceCreated={handleInstanceCreated}
|
||||||
{/* Mensagem quando já tem instância conectada */}
|
onViewQrCode={handleViewQrCode}
|
||||||
{hasExistingInstance && existingInstanceData && (
|
|
||||||
<div className="bg-green-50 border border-green-200 rounded-lg p-4">
|
|
||||||
<div className="flex items-center">
|
|
||||||
<div className="flex-shrink-0">
|
|
||||||
<svg className="h-5 w-5 text-green-400" viewBox="0 0 20 20" fill="currentColor">
|
|
||||||
<path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clipRule="evenodd" />
|
|
||||||
</svg>
|
|
||||||
</div>
|
|
||||||
<div className="ml-3">
|
|
||||||
<h3 className="text-sm font-medium text-green-800">
|
|
||||||
WhatsApp Conectado ✅
|
|
||||||
</h3>
|
|
||||||
<div className="mt-2 text-sm text-green-700">
|
|
||||||
<p>Você já possui uma instância do WhatsApp conectada: <strong>{existingInstanceData.instancia_zap}</strong></p>
|
|
||||||
<p>Status: <strong>{existingInstanceData.status_instancia}</strong></p>
|
|
||||||
<p>Agora você pode criar grupos WhatsApp!</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{hasInstances && <InstanceStats instances={instances} />}
|
|
||||||
|
|
||||||
<InstanceList
|
|
||||||
instances={instances}
|
|
||||||
onViewQrCode={handleViewQrCode}
|
|
||||||
onDelete={handleDeleteInstanceWrapper}
|
onDelete={handleDeleteInstanceWrapper}
|
||||||
onRestart={handleRestartInstance}
|
onRestart={handleRestartInstance}
|
||||||
onLogout={handleLogoutInstance}
|
onLogout={handleLogoutInstance}
|
||||||
onDisconnect={handleDisconnectInstance}
|
onDisconnect={handleDisconnectInstance}
|
||||||
onSetPresence={handleSetPresence}
|
onSetPresence={handleSetPresence}
|
||||||
onRefreshInstances={refreshInstances}
|
onRefreshInstances={refreshInstances}
|
||||||
isRefreshing={isRefreshing}
|
|
||||||
/>
|
|
||||||
|
|
||||||
<QrCodeDialog
|
|
||||||
open={qrDialogOpen}
|
|
||||||
onOpenChange={setQrDialogOpen}
|
|
||||||
activeInstance={activeInstance}
|
|
||||||
onStatusCheck={checkAllInstancesStatus}
|
onStatusCheck={checkAllInstancesStatus}
|
||||||
|
setQrDialogOpen={setQrDialogOpen}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</Layout>
|
</Layout>
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user