From 2c2dfba45357bbd205a59145ae55a2779c911ae0 Mon Sep 17 00:00:00 2001 From: Lucas Faria Mendes Date: Fri, 14 Aug 2026 15:06:35 -0300 Subject: remake Signed-off-by: Lucas Faria Mendes --- src/screens/dashboard-screen.tsx | 440 +++++++++++++++++++++++++++ src/screens/one-time-expenses-screen.tsx | 485 ++++++++++++++++++++++++++++++ src/screens/recurring-expenses-screen.tsx | 442 +++++++++++++++++++++++++++ src/screens/salary-screen.tsx | 232 ++++++++++++++ 4 files changed, 1599 insertions(+) create mode 100644 src/screens/dashboard-screen.tsx create mode 100644 src/screens/one-time-expenses-screen.tsx create mode 100644 src/screens/recurring-expenses-screen.tsx create mode 100644 src/screens/salary-screen.tsx (limited to 'src/screens') diff --git a/src/screens/dashboard-screen.tsx b/src/screens/dashboard-screen.tsx new file mode 100644 index 0000000..c4a533c --- /dev/null +++ b/src/screens/dashboard-screen.tsx @@ -0,0 +1,440 @@ +import React, { useCallback, useState } from 'react'; +import { + ActivityIndicator, + RefreshControl, + ScrollView, + StyleSheet, + Text, + TouchableOpacity, + View, +} from 'react-native'; +import { Feather } from '@expo/vector-icons'; +import { LinearGradient } from 'expo-linear-gradient'; +import Animated, { + FadeInDown, + FadeInUp, + LinearTransition, +} from 'react-native-reanimated'; +import { useSafeAreaInsets } from 'react-native-safe-area-context'; +import { Card, CurrencyDisplay, Divider, SectionLabel } from '@/components/ui/primitives'; +import { ExpensesChart } from '@/components/ui/expenses-chart'; +import { Colors, Spacing, Typography } from '@/constants/theme'; +import { getDashboard } from '@/services/api'; +import type { DashboardData } from '@/types'; +import { useAuth } from '@/contexts/AuthContext'; +import { useRouter, useFocusEffect } from 'expo-router'; +import { useIsFocused } from "expo-router/react-navigation"; + +const MONTH_NAMES = [ + '', 'Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', + 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro', +]; + +export default function DashboardScreen() { + const insets = useSafeAreaInsets(); + const [refreshing, setRefreshing] = useState(false); + const [data, setData] = useState(null); + const [loading, setLoading] = useState(true); + const [error, setError] = useState(null); + const { user, logout } = useAuth(); + const router = useRouter(); + const isFocused = useIsFocused(); + + const [targetMonth, setTargetMonth] = useState(() => new Date().getMonth() + 1); + const [targetYear, setTargetYear] = useState(() => new Date().getFullYear()); + + const fetchDashboard = useCallback(async () => { + if (!user) return; + try { + setError(null); + const res = await getDashboard(user.id, targetMonth, targetYear); + setData(res); + } catch (err) { + setError('Não foi possível carregar os dados.'); + } finally { + setLoading(false); + } + }, [targetMonth, targetYear, user]); + + useFocusEffect( + useCallback(() => { + fetchDashboard(); + }, [fetchDashboard]) + ); + + async function handleRefresh() { + setRefreshing(true); + await fetchDashboard(); + setRefreshing(false); + } + + if (loading) { + return ( + + + + ); + } + + if (error || !data) { + return ( + + {error} + + ); + } + + const isPositive = data.balance.available >= 0; + const monthName = MONTH_NAMES[data.period.month]; + + return ( + + + + {isFocused && ( + + } + > + + + Olá, {data.user.name} 👋 + + + { + let m = targetMonth - 1; + let y = targetYear; + if (m < 1) { m = 12; y -= 1; } + setTargetMonth(m); + setTargetYear(y); + setLoading(true); + }} + style={styles.monthButton} + > + + + + + {monthName} {data.period.year} + + + { + let m = targetMonth + 1; + let y = targetYear; + if (m > 12) { m = 1; y += 1; } + setTargetMonth(m); + setTargetYear(y); + setLoading(true); + }} + style={styles.monthButton} + > + + + + + + { + await logout(); + router.replace('/login'); + }} + > + + + + + + + + + + + + + + 80 ? Colors.negative : Colors.primary, + }, + ]} + /> + + + {data.balance.expense_ratio.toFixed(1)}% do salário comprometido + + + + + + + + + + + Bruto + + {data.salary.gross.toLocaleString('pt-BR', { + style: 'currency', + currency: 'BRL', + minimumFractionDigits: 0, + })} + + + + → + + + Líquido + + {data.salary.effective_net.toLocaleString('pt-BR', { + style: 'currency', + currency: 'BRL', + minimumFractionDigits: 0, + })} + + + + + + INSS + + -{data.salary.inss_discount.toLocaleString('pt-BR', { + style: 'currency', + currency: 'BRL', + })} + + + + IRRF + + -{data.salary.irrf_discount.toLocaleString('pt-BR', { + style: 'currency', + currency: 'BRL', + })} + + + + + + + + + + + + + + + {data.expenses.recurring_total < 0 ? '+ ' : (data.expenses.recurring_total > 0 ? '- ' : '')} + {Math.abs(data.expenses.recurring_total).toLocaleString('pt-BR', { + style: 'currency', + currency: 'BRL', + minimumFractionDigits: 0, + })} + + + + + + + + + + + {data.expenses.one_time_total < 0 ? '+ ' : (data.expenses.one_time_total > 0 ? '- ' : '')} + {Math.abs(data.expenses.one_time_total).toLocaleString('pt-BR', { + style: 'currency', + currency: 'BRL', + minimumFractionDigits: 0, + })} + + + + + + )} + + ); +} + +const styles = StyleSheet.create({ + container: { + flex: 1, + backgroundColor: Colors.background, + }, + centered: { + justifyContent: 'center', + alignItems: 'center', + }, + errorText: { + ...Typography.body, + color: Colors.negative, + }, + headerGradient: { + position: 'absolute', + top: 0, + left: 0, + right: 0, + height: 200, + }, + scroll: { + padding: Spacing.md, + gap: Spacing.md, + }, + headerTop: { + flexDirection: 'row', + justifyContent: 'space-between', + alignItems: 'flex-start', + paddingVertical: Spacing.sm, + }, + greeting: { + flex: 1, + }, + logoutBtn: { + padding: 8, + backgroundColor: 'rgba(255,255,255,0.05)', + borderRadius: 12, + }, + greetingText: { + ...Typography.h2, + color: Colors.textPrimary, + }, + periodText: { + ...Typography.caption, + color: Colors.textSecondary, + textTransform: 'uppercase', + letterSpacing: 1.5, + }, + monthSelector: { + flexDirection: 'row', + alignItems: 'center', + marginTop: 6, + gap: Spacing.xs, + }, + monthButton: { + padding: 4, + }, + card: { + gap: Spacing.sm, + }, + heroCard: { + gap: Spacing.md, + borderWidth: 1, + }, + heroPositive: { + borderColor: `${Colors.positive}40`, + }, + heroNegative: { + borderColor: `${Colors.negative}40`, + }, + heroBalance: { + marginTop: Spacing.xs, + }, + ratioSection: { + gap: Spacing.xs, + }, + ratioBar: { + height: 4, + backgroundColor: Colors.border, + borderRadius: 2, + overflow: 'hidden', + }, + ratioFill: { + height: '100%', + borderRadius: 2, + }, + ratioText: { + ...Typography.caption, + color: Colors.textMuted, + }, + salaryRow: { + flexDirection: 'row', + alignItems: 'center', + justifyContent: 'space-between', + marginTop: Spacing.sm, + }, + salaryItem: { + flex: 1, + gap: 4, + }, + salaryLabel: { + ...Typography.caption, + color: Colors.textMuted, + textTransform: 'uppercase', + letterSpacing: 1, + }, + salaryValue: { + ...Typography.h2, + color: Colors.textPrimary, + }, + salaryArrow: { + paddingHorizontal: Spacing.md, + }, + salaryArrowText: { + ...Typography.h2, + color: Colors.textMuted, + }, + taxRow: { + flexDirection: 'row', + justifyContent: 'space-between', + alignItems: 'center', + }, + taxLabel: { + ...Typography.body, + color: Colors.textSecondary, + }, + taxValue: { + ...Typography.body, + color: Colors.negative, + fontFamily: 'DMSans_600SemiBold', + }, + sectionHeader: { + flexDirection: 'row', + justifyContent: 'space-between', + alignItems: 'center', + marginBottom: Spacing.xs, + }, + totalBadge: { + ...Typography.body, + color: Colors.negative, + fontFamily: 'DMSans_600SemiBold', + }, + rowDivider: { + marginVertical: 0, + }, +}); diff --git a/src/screens/one-time-expenses-screen.tsx b/src/screens/one-time-expenses-screen.tsx new file mode 100644 index 0000000..c84a39f --- /dev/null +++ b/src/screens/one-time-expenses-screen.tsx @@ -0,0 +1,485 @@ +import React, { useCallback, useState } from 'react'; +import { + Alert, + ScrollView, + StyleSheet, + Text, + TouchableOpacity, + View, +} from 'react-native'; +import Animated, { FadeInDown, LinearTransition } from 'react-native-reanimated'; +import { useSafeAreaInsets } from 'react-native-safe-area-context'; +import * as Haptics from 'expo-haptics'; +import { Button } from '@/components/ui/button'; +import { Input } from '@/components/ui/input'; +import { Card, Divider, SectionLabel } from '@/components/ui/primitives'; +import { OneTimeExpenseRow } from '@/components/expense-row'; +import { Colors, Radius, Spacing, Typography } from '@/constants/theme'; +import type { Category, OneTimeExpense } from '@/types'; +import { + createOneTimeExpense, + updateOneTimeExpense, + deleteOneTimeExpense, + getOneTimeExpenses, +} from '@/services/api'; +import { useAuth } from '@/contexts/AuthContext'; +import { ActionModal } from '@/components/ui/action-modal'; +import { OptionsModal } from '@/components/ui/options-modal'; +import { useFocusEffect } from 'expo-router'; +import { useIsFocused } from "expo-router/react-navigation"; + +const CATEGORIES: { value: Category; emoji: string; label: string }[] = [ + { value: 'alimentação', emoji: '🍽️', label: 'Alimentação' }, + { value: 'lazer', emoji: '🎬', label: 'Lazer' }, + { value: 'transporte', emoji: '🚗', label: 'Transporte' }, + { value: 'saúde', emoji: '💊', label: 'Saúde' }, + { value: 'moradia', emoji: '🏠', label: 'Moradia' }, + { value: 'educação', emoji: '📚', label: 'Educação' }, + { value: 'serviços', emoji: '⚙️', label: 'Serviços' }, + { value: 'outros', emoji: '📦', label: 'Outros' }, +]; + +export default function OneTimeExpensesScreen() { + const insets = useSafeAreaInsets(); + const { user } = useAuth(); + const [expenses, setExpenses] = useState([]); + const [showForm, setShowForm] = useState(false); + const [loading, setLoading] = useState(true); + + const [name, setName] = useState(''); + const [amount, setAmount] = useState(''); + const [selectedCategory, setSelectedCategory] = useState('outros'); + const [expenseType, setExpenseType] = useState<'expense' | 'income'>('expense'); + const [notes, setNotes] = useState(''); + const [isSubmitting, setIsSubmitting] = useState(false); + + const [expenseToDelete, setExpenseToDelete] = useState(null); + const [selectedExpense, setSelectedExpense] = useState(null); + const [editingExpenseId, setEditingExpenseId] = useState(null); + + const isFocused = useIsFocused(); + + const fetchExpenses = useCallback(async () => { + if (!user) return; + try { + setLoading(true); + const data = await getOneTimeExpenses(user.id); + setExpenses(data); + } catch (err) { + Alert.alert('Erro', 'Não foi possível carregar os gastos do mês.'); + } finally { + setLoading(false); + } + }, [user]); + + useFocusEffect( + useCallback(() => { + fetchExpenses(); + }, [fetchExpenses]) + ); + + const monthTotal = expenses.reduce((sum, e) => { + return sum + (e.type === 'income' ? -e.amount : e.amount); + }, 0); + const isTotalIncome = monthTotal < 0; + const absTotal = Math.abs(monthTotal); + const formattedTotal = absTotal.toLocaleString('pt-BR', { + style: 'currency', + currency: 'BRL', + }); + + async function handleAdd() { + const amountNum = parseFloat(amount.replace(',', '.')); + if (!name.trim() || isNaN(amountNum) || amountNum <= 0) { + Alert.alert('Dados inválidos', 'Preencha o nome e um valor válido.'); + return; + } + + try { + if (!user) return; + setIsSubmitting(true); + + if (editingExpenseId) { + const updated = await updateOneTimeExpense(user.id, editingExpenseId, { + name: name.trim(), + amount: amountNum, + category: selectedCategory, + type: expenseType, + notes: notes.trim() || null, + }); + setExpenses((prev) => prev.map((e) => e.id === editingExpenseId ? updated : e)); + Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success); + } else { + const today = new Date().toISOString().split('T')[0]; + const newExpense = await createOneTimeExpense(user.id, { + name: name.trim(), + amount: amountNum, + category: selectedCategory, + type: expenseType, + expense_date: today, + notes: notes.trim() || null, + }); + setExpenses((prev) => [...prev, newExpense]); + Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success); + } + + setName(''); + setAmount(''); + setNotes(''); + setExpenseType('expense'); + setShowForm(false); + setEditingExpenseId(null); + } catch (err) { + Alert.alert('Erro', 'Não foi possível salvar o lançamento.'); + } finally { + setIsSubmitting(false); + } + } + + function handleDelete(id: number) { + setExpenseToDelete(id); + setSelectedExpense(null); + } + + function handleEdit(expense: OneTimeExpense) { + setName(expense.name); + setAmount(expense.amount.toString()); + setSelectedCategory(expense.category); + setExpenseType(expense.type); + setNotes(expense.notes || ''); + setEditingExpenseId(expense.id); + setSelectedExpense(null); + setShowForm(true); + } + + async function confirmDelete() { + if (!user || expenseToDelete === null) return; + Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Medium); + try { + await deleteOneTimeExpense(user.id, expenseToDelete); + setExpenses((prev) => prev.filter((e) => e.id !== expenseToDelete)); + } catch (err) { + Alert.alert('Erro', 'Não foi possível remover o lançamento.'); + } finally { + setExpenseToDelete(null); + } + } + + return ( + + {isFocused && ( + + + + Lançamentos + + Saldo líquido:{' '} + + {isTotalIncome ? '+ ' : (monthTotal > 0 ? '- ' : '')}{formattedTotal} + + + + { + if (showForm) { + setEditingExpenseId(null); + setName(''); + setAmount(''); + setNotes(''); + } + setShowForm((v) => !v); + }} + accessibilityLabel="Adicionar lançamento" + accessibilityRole="button" + > + {showForm ? '✕' : '+'} + + + + {showForm && ( + + + + + + setExpenseType('expense')} + > + + Despesa + + + setExpenseType('income')} + > + + Receita + + + + + + + + + + Categoria + + {CATEGORIES.map((cat) => ( + setSelectedCategory(cat.value)} + accessibilityLabel={cat.label} + accessibilityRole="radio" + > + {cat.emoji} + + {cat.label} + + + ))} + + + + + +