Reverted to commit 4aaeebc28c
This commit is contained in:
parent
e5ea61feee
commit
9cf58548c0
@ -1,20 +1,29 @@
|
|||||||
|
|
||||||
import React, { useState, useEffect } from 'react';
|
import React, { useState } from 'react';
|
||||||
import { supabase } from '@/integrations/supabase/client';
|
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||||
import { useToast } from '@/hooks/use-toast';
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
import { Button } from '@/components/ui/button';
|
||||||
import { Badge } from '@/components/ui/badge';
|
import { Badge } from '@/components/ui/badge';
|
||||||
|
import { supabase } from '@/integrations/supabase/client';
|
||||||
|
import { useAuthStore } from '@/stores/authStore';
|
||||||
|
import { Edit, Trash2, Calendar, Clock, DollarSign, Bell } from 'lucide-react';
|
||||||
|
import { toast } from 'sonner';
|
||||||
|
import { format } from 'date-fns';
|
||||||
|
import { ptBR } from 'date-fns/locale';
|
||||||
import FiltroMesAno from './FiltroMesAno';
|
import FiltroMesAno from './FiltroMesAno';
|
||||||
import StatusTags from './StatusTags';
|
import StatusTags from './StatusTags';
|
||||||
|
|
||||||
interface ContaRecorrente {
|
interface ContaRecorrente {
|
||||||
id: string;
|
id: string;
|
||||||
nome: string;
|
nome_conta: string;
|
||||||
valor: number;
|
descricao: string | null;
|
||||||
|
valor: number | null;
|
||||||
dia_vencimento: number;
|
dia_vencimento: number;
|
||||||
email_usuario: string;
|
hora_aviso: string;
|
||||||
ativa: boolean;
|
dias_antecedencia: number;
|
||||||
|
ativo: boolean;
|
||||||
created_at: string;
|
created_at: string;
|
||||||
|
email_usuario: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface StatusPagamento {
|
interface StatusPagamento {
|
||||||
@ -28,149 +37,277 @@ interface AvisoEnviado {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const ContasRecorrentesList = () => {
|
const ContasRecorrentesList = () => {
|
||||||
const [contas, setContas] = useState<ContaRecorrente[]>([]);
|
const { user, session } = useAuthStore();
|
||||||
const [statusPagamentos, setStatusPagamentos] = useState<{[key: string]: StatusPagamento}>({});
|
const queryClient = useQueryClient();
|
||||||
const [avisosEnviados, setAvisosEnviados] = useState<{[key: string]: AvisoEnviado}>({});
|
const [deletingId, setDeletingId] = useState<string | null>(null);
|
||||||
const [loading, setLoading] = useState(true);
|
const [hoveredCard, setHoveredCard] = useState<string | null>(null);
|
||||||
const [mesAno, setMesAno] = useState(() => {
|
|
||||||
const now = new Date();
|
// Estado para filtro de mês/ano - inicializa com mês/ano atual
|
||||||
return { mes: now.getMonth() + 1, ano: now.getFullYear() };
|
const dataAtual = new Date();
|
||||||
|
const [mesAno, setMesAno] = useState({
|
||||||
|
mes: dataAtual.getMonth() + 1,
|
||||||
|
ano: dataAtual.getFullYear()
|
||||||
});
|
});
|
||||||
const { toast } = useToast();
|
|
||||||
|
|
||||||
const formatCurrency = (value: number) => {
|
// Buscar email do usuário logado
|
||||||
|
const userEmail = session?.user?.email || user?.email;
|
||||||
|
|
||||||
|
const { data: contas, isLoading } = useQuery({
|
||||||
|
queryKey: ['contas-recorrentes', userEmail],
|
||||||
|
queryFn: async () => {
|
||||||
|
if (!userEmail) return [];
|
||||||
|
|
||||||
|
const { data, error } = await supabase
|
||||||
|
.from('contas_recorrentes')
|
||||||
|
.select('*')
|
||||||
|
.eq('email_usuario', userEmail)
|
||||||
|
.order('created_at', { ascending: false });
|
||||||
|
|
||||||
|
if (error) throw error;
|
||||||
|
return data as ContaRecorrente[];
|
||||||
|
},
|
||||||
|
enabled: !!userEmail
|
||||||
|
});
|
||||||
|
|
||||||
|
// Buscar status de pagamento para todas as contas do período selecionado
|
||||||
|
const { data: statusPagamentos } = useQuery({
|
||||||
|
queryKey: ['status-pagamentos', mesAno.mes, mesAno.ano, contas?.map(c => c.id)],
|
||||||
|
queryFn: async () => {
|
||||||
|
if (!contas || contas.length === 0) return {};
|
||||||
|
|
||||||
|
const { data, error } = await supabase
|
||||||
|
.from('status_pagamento_mensal')
|
||||||
|
.select('conta_id, status, valor_pago, data_pagamento')
|
||||||
|
.in('conta_id', contas.map(c => c.id))
|
||||||
|
.eq('mes', mesAno.mes)
|
||||||
|
.eq('ano', mesAno.ano);
|
||||||
|
|
||||||
|
if (error) throw error;
|
||||||
|
|
||||||
|
// Converter array em objeto indexado por conta_id
|
||||||
|
const statusMap: Record<string, StatusPagamento> = {};
|
||||||
|
data?.forEach(status => {
|
||||||
|
statusMap[status.conta_id] = status;
|
||||||
|
});
|
||||||
|
|
||||||
|
return statusMap;
|
||||||
|
},
|
||||||
|
enabled: !!contas && contas.length > 0
|
||||||
|
});
|
||||||
|
|
||||||
|
// Buscar avisos enviados para todas as contas do período selecionado
|
||||||
|
const { data: avisosEnviados } = useQuery({
|
||||||
|
queryKey: ['avisos-enviados', mesAno.mes, mesAno.ano, contas?.map(c => c.id)],
|
||||||
|
queryFn: async () => {
|
||||||
|
if (!contas || contas.length === 0) return {};
|
||||||
|
|
||||||
|
// Criar range de datas para o mês/ano selecionado
|
||||||
|
const inicioMes = new Date(mesAno.ano, mesAno.mes - 1, 1);
|
||||||
|
const fimMes = new Date(mesAno.ano, mesAno.mes, 0);
|
||||||
|
|
||||||
|
const { data, error } = await supabase
|
||||||
|
.from('avisos_enviados')
|
||||||
|
.select('conta_id, data_aviso')
|
||||||
|
.in('conta_id', contas.map(c => c.id))
|
||||||
|
.gte('data_aviso', inicioMes.toISOString().split('T')[0])
|
||||||
|
.lte('data_aviso', fimMes.toISOString().split('T')[0]);
|
||||||
|
|
||||||
|
if (error) throw error;
|
||||||
|
|
||||||
|
// Converter array em objeto indexado por conta_id (pega o primeiro aviso do mês)
|
||||||
|
const avisosMap: Record<string, AvisoEnviado> = {};
|
||||||
|
data?.forEach(aviso => {
|
||||||
|
if (!avisosMap[aviso.conta_id]) {
|
||||||
|
avisosMap[aviso.conta_id] = aviso;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return avisosMap;
|
||||||
|
},
|
||||||
|
enabled: !!contas && contas.length > 0
|
||||||
|
});
|
||||||
|
|
||||||
|
const handleDelete = async (id: string) => {
|
||||||
|
setDeletingId(id);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const { error } = await supabase
|
||||||
|
.from('contas_recorrentes')
|
||||||
|
.delete()
|
||||||
|
.eq('id', id);
|
||||||
|
|
||||||
|
if (error) throw error;
|
||||||
|
|
||||||
|
toast.success('Conta removida com sucesso!');
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['contas-recorrentes'] });
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Erro ao remover conta:', error);
|
||||||
|
toast.error('Erro ao remover conta. Tente novamente.');
|
||||||
|
} finally {
|
||||||
|
setDeletingId(null);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const toggleAtivo = async (id: string, ativo: boolean) => {
|
||||||
|
try {
|
||||||
|
const { error } = await supabase
|
||||||
|
.from('contas_recorrentes')
|
||||||
|
.update({ ativo: !ativo })
|
||||||
|
.eq('id', id);
|
||||||
|
|
||||||
|
if (error) throw error;
|
||||||
|
|
||||||
|
toast.success(ativo ? 'Conta desativada' : 'Conta ativada');
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['contas-recorrentes'] });
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Erro ao alterar status:', error);
|
||||||
|
toast.error('Erro ao alterar status da conta.');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const formatCurrency = (value: number | null) => {
|
||||||
|
if (value === null) return 'Não informado';
|
||||||
return new Intl.NumberFormat('pt-BR', {
|
return new Intl.NumberFormat('pt-BR', {
|
||||||
style: 'currency',
|
style: 'currency',
|
||||||
currency: 'BRL'
|
currency: 'BRL'
|
||||||
}).format(value);
|
}).format(value);
|
||||||
};
|
};
|
||||||
|
|
||||||
const loadContas = async () => {
|
if (isLoading) {
|
||||||
try {
|
|
||||||
setLoading(true);
|
|
||||||
|
|
||||||
// Buscar dados do usuário logado
|
|
||||||
const { data: { user } } = await supabase.auth.getUser();
|
|
||||||
if (!user?.email) {
|
|
||||||
console.error('Usuário não logado');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
console.log('Buscando contas para o usuário:', user.email);
|
|
||||||
|
|
||||||
// Buscar contas recorrentes do usuário
|
|
||||||
const { data: contasData, error: contasError } = await supabase
|
|
||||||
.from('contas_recorrentes')
|
|
||||||
.select('*')
|
|
||||||
.eq('email_usuario', user.email)
|
|
||||||
.eq('ativa', true)
|
|
||||||
.order('nome');
|
|
||||||
|
|
||||||
if (contasError) {
|
|
||||||
console.error('Erro ao buscar contas:', contasError);
|
|
||||||
throw contasError;
|
|
||||||
}
|
|
||||||
|
|
||||||
console.log('Contas encontradas:', contasData);
|
|
||||||
setContas(contasData || []);
|
|
||||||
|
|
||||||
// Buscar status de pagamento para cada conta no mês/ano selecionado
|
|
||||||
const statusMap: {[key: string]: StatusPagamento} = {};
|
|
||||||
const avisosMap: {[key: string]: AvisoEnviado} = {};
|
|
||||||
|
|
||||||
for (const conta of contasData || []) {
|
|
||||||
// Buscar status de pagamento
|
|
||||||
const { data: statusData } = await supabase
|
|
||||||
.from('status_pagamento_mensal')
|
|
||||||
.select('status, valor_pago, data_pagamento')
|
|
||||||
.eq('conta_id', conta.id)
|
|
||||||
.eq('mes', mesAno.mes)
|
|
||||||
.eq('ano', mesAno.ano)
|
|
||||||
.single();
|
|
||||||
|
|
||||||
if (statusData) {
|
|
||||||
statusMap[conta.id] = statusData;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Buscar aviso enviado
|
|
||||||
const { data: avisoData } = await supabase
|
|
||||||
.from('avisos_enviados')
|
|
||||||
.select('data_aviso')
|
|
||||||
.eq('conta_id', conta.id)
|
|
||||||
.gte('data_aviso', `${mesAno.ano}-${String(mesAno.mes).padStart(2, '0')}-01`)
|
|
||||||
.lt('data_aviso', `${mesAno.ano}-${String(mesAno.mes + 1).padStart(2, '0')}-01`)
|
|
||||||
.single();
|
|
||||||
|
|
||||||
if (avisoData) {
|
|
||||||
avisosMap[conta.id] = avisoData;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
setStatusPagamentos(statusMap);
|
|
||||||
setAvisosEnviados(avisosMap);
|
|
||||||
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Erro ao carregar contas:', error);
|
|
||||||
toast({
|
|
||||||
title: "Erro ao carregar contas",
|
|
||||||
description: "Não foi possível carregar as contas recorrentes",
|
|
||||||
variant: "destructive"
|
|
||||||
});
|
|
||||||
} finally {
|
|
||||||
setLoading(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
loadContas();
|
|
||||||
}, [mesAno]);
|
|
||||||
|
|
||||||
if (loading) {
|
|
||||||
return (
|
return (
|
||||||
<div className="flex justify-center items-center h-64">
|
<Card>
|
||||||
<div className="text-lg">Carregando contas...</div>
|
<CardContent className="p-6">
|
||||||
</div>
|
<div className="text-center">Carregando contas...</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!userEmail) {
|
||||||
|
return (
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle>Suas Contas Recorrentes</CardTitle>
|
||||||
|
<CardDescription>Você precisa estar logado para ver suas contas</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
</Card>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
|
{/* Filtro de Mês/Ano */}
|
||||||
<FiltroMesAno mesAno={mesAno} onMesAnoChange={setMesAno} />
|
<FiltroMesAno mesAno={mesAno} onMesAnoChange={setMesAno} />
|
||||||
|
|
||||||
{contas.length === 0 ? (
|
{/* Lista de Contas */}
|
||||||
|
{!contas || contas.length === 0 ? (
|
||||||
<Card>
|
<Card>
|
||||||
<CardContent className="p-6">
|
<CardHeader>
|
||||||
<p className="text-center text-gray-500">
|
<CardTitle>Suas Contas Recorrentes</CardTitle>
|
||||||
Nenhuma conta recorrente encontrada para o período selecionado.
|
<CardDescription>Você ainda não cadastrou nenhuma conta recorrente</CardDescription>
|
||||||
</p>
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<div className="text-center py-8">
|
||||||
|
<Bell className="h-12 w-12 text-gray-400 mx-auto mb-4" />
|
||||||
|
<p className="text-gray-500">Clique em "Nova Conta" para começar</p>
|
||||||
|
</div>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
) : (
|
) : (
|
||||||
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
|
<div className="space-y-4">
|
||||||
{contas.map((conta) => (
|
<h2 className="text-xl font-semibold">
|
||||||
<Card key={conta.id} className="relative">
|
Suas Contas Recorrentes - {mesAno.mes.toString().padStart(2, '0')}/{mesAno.ano}
|
||||||
<CardHeader>
|
</h2>
|
||||||
<CardTitle className="flex justify-between items-start">
|
|
||||||
<span>{conta.nome}</span>
|
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
|
||||||
<Badge variant="outline" className="ml-2">
|
{contas.map((conta) => (
|
||||||
Dia {conta.dia_vencimento}
|
<div
|
||||||
</Badge>
|
key={conta.id}
|
||||||
</CardTitle>
|
className="relative group"
|
||||||
</CardHeader>
|
onMouseEnter={() => setHoveredCard(conta.id)}
|
||||||
<CardContent>
|
onMouseLeave={() => setHoveredCard(null)}
|
||||||
<div className="space-y-3">
|
>
|
||||||
<div className="text-xl font-bold text-green-600">
|
{hoveredCard === conta.id && (
|
||||||
{formatCurrency(conta.valor)}
|
<div className="absolute inset-0 bg-gradient-to-r from-blue-400/20 to-purple-400/20 rounded-lg blur-xl transition-all duration-300 ease-in-out" />
|
||||||
</div>
|
)}
|
||||||
|
|
||||||
|
<Card className={`
|
||||||
|
relative z-10 transition-all duration-300 ease-in-out
|
||||||
|
${conta.ativo ? 'hover:shadow-lg hover:scale-105' : 'opacity-60 hover:opacity-80'}
|
||||||
|
${hoveredCard === conta.id ? 'border-blue-300 shadow-lg' : ''}
|
||||||
|
`}>
|
||||||
|
<CardHeader className="pb-3">
|
||||||
|
<div className="flex items-start justify-between">
|
||||||
|
<div className="flex-1">
|
||||||
|
<CardTitle className="text-lg">{conta.nome_conta}</CardTitle>
|
||||||
|
{conta.descricao && (
|
||||||
|
<CardDescription className="mt-1">{conta.descricao}</CardDescription>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<Badge variant={conta.ativo ? 'default' : 'secondary'}>
|
||||||
|
{conta.ativo ? 'Ativo' : 'Inativo'}
|
||||||
|
</Badge>
|
||||||
|
</div>
|
||||||
|
</CardHeader>
|
||||||
|
|
||||||
<StatusTags
|
<CardContent className="space-y-3">
|
||||||
statusPagamento={statusPagamentos[conta.id] || null}
|
{/* Tags de Status */}
|
||||||
avisoEnviado={avisosEnviados[conta.id] || null}
|
<StatusTags
|
||||||
/>
|
statusPagamento={statusPagamentos?.[conta.id] || null}
|
||||||
</div>
|
avisoEnviado={avisosEnviados?.[conta.id] || null}
|
||||||
</CardContent>
|
/>
|
||||||
</Card>
|
|
||||||
))}
|
<div className="space-y-2">
|
||||||
|
<div className="flex items-center gap-2 text-sm">
|
||||||
|
<DollarSign className="h-4 w-4 text-green-600" />
|
||||||
|
<span className="font-medium">Valor:</span>
|
||||||
|
<span>{formatCurrency(conta.valor)}</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-2 text-sm">
|
||||||
|
<Calendar className="h-4 w-4 text-blue-600" />
|
||||||
|
<span className="font-medium">Vencimento:</span>
|
||||||
|
<span>Todo dia {conta.dia_vencimento}</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-2 text-sm">
|
||||||
|
<Clock className="h-4 w-4 text-purple-600" />
|
||||||
|
<span className="font-medium">Horário:</span>
|
||||||
|
<span>{conta.hora_aviso}</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-2 text-sm">
|
||||||
|
<Bell className="h-4 w-4 text-orange-600" />
|
||||||
|
<span className="font-medium">Antecedência:</span>
|
||||||
|
<span>{conta.dias_antecedencia} dia(s)</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex gap-2 pt-2 border-t">
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => toggleAtivo(conta.id, conta.ativo)}
|
||||||
|
className="flex-1"
|
||||||
|
>
|
||||||
|
{conta.ativo ? 'Desativar' : 'Ativar'}
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => handleDelete(conta.id)}
|
||||||
|
disabled={deletingId === conta.id}
|
||||||
|
className="text-red-600 hover:text-red-700"
|
||||||
|
>
|
||||||
|
<Trash2 className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@ -1,3 +1,4 @@
|
|||||||
|
|
||||||
import { Menu, User, LogOut } from 'lucide-react';
|
import { Menu, User, LogOut } from 'lucide-react';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { useIsMobile } from '@/hooks/use-mobile';
|
import { useIsMobile } from '@/hooks/use-mobile';
|
||||||
@ -64,10 +65,10 @@ export default function Header({ onMenuToggle }: HeaderProps) {
|
|||||||
<Button
|
<Button
|
||||||
variant="outline"
|
variant="outline"
|
||||||
size="icon"
|
size="icon"
|
||||||
className="shrink-0 md:hidden h-12 w-12 p-3"
|
className="shrink-0 md:hidden"
|
||||||
onClick={onMenuToggle}
|
onClick={onMenuToggle}
|
||||||
>
|
>
|
||||||
<Menu className="h-6 w-6" />
|
<Menu className="h-5 w-5" />
|
||||||
<span className="sr-only">Toggle navigation menu</span>
|
<span className="sr-only">Toggle navigation menu</span>
|
||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@ -132,7 +132,7 @@ export const MobileSidebar = ({
|
|||||||
</div>
|
</div>
|
||||||
<div className="flex justify-end z-20">
|
<div className="flex justify-end z-20">
|
||||||
<Menu
|
<Menu
|
||||||
className="text-neutral-800 dark:text-neutral-200 h-8 w-8 cursor-pointer p-1 hover:bg-gray-100 rounded-md transition-colors"
|
className="text-neutral-800 dark:text-neutral-200 h-6 w-6 cursor-pointer"
|
||||||
onClick={() => setOpen(!open)}
|
onClick={() => setOpen(!open)}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
@ -152,7 +152,7 @@ export const MobileSidebar = ({
|
|||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
<div
|
<div
|
||||||
className="absolute right-6 top-6 z-50 text-neutral-800 dark:text-neutral-200 cursor-pointer p-2 hover:bg-gray-100 rounded-md transition-colors"
|
className="absolute right-6 top-6 z-50 text-neutral-800 dark:text-neutral-200 cursor-pointer"
|
||||||
onClick={() => setOpen(!open)}
|
onClick={() => setOpen(!open)}
|
||||||
>
|
>
|
||||||
<X className="h-6 w-6" />
|
<X className="h-6 w-6" />
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user