Refactor: Split Analytics page

Splits the Analytics page into smaller, more manageable components to improve code organization and maintainability.
This commit is contained in:
gpt-engineer-app[bot]
2025-03-16 05:51:34 +00:00
parent 650bbf2f6f
commit 71d21b9e6e
5 changed files with 250 additions and 133 deletions

View File

@@ -0,0 +1,62 @@
import React from 'react';
import { formatCurrency } from '@/utils/formatters';
interface CategorySpending {
title: string;
current: number;
total: number;
}
interface CategorySpendingListProps {
categories: CategorySpending[];
totalExpense: number;
}
const CategorySpendingList: React.FC<CategorySpendingListProps> = ({
categories,
totalExpense
}) => {
// 카테고리별 색상 매핑
const getCategoryColor = (title: string) => {
switch (title) {
case '식비': return '#81c784';
case '생활비': return '#AED581';
case '교통비': return '#2E7D32';
default: return '#4CAF50';
}
};
return (
<div className="neuro-card mb-6">
{categories.some(cat => cat.current > 0) ? (
<div className="space-y-4">
{categories.map((category) => (
<div key={category.title} className="flex items-center justify-between">
<div className="flex items-center gap-3">
<div className="w-6 h-6 rounded-full" style={{
backgroundColor: getCategoryColor(category.title)
}}></div>
<span>{category.title}</span>
</div>
<div className="text-right">
<p className="font-medium">
{formatCurrency(category.current)}
</p>
<p className="text-xs text-gray-500">
{totalExpense > 0 ? Math.round(category.current / totalExpense * 100) : 0}%
</p>
</div>
</div>
))}
</div>
) : (
<div className="py-8 text-center text-gray-400">
<p> </p>
</div>
)}
</div>
);
};
export default CategorySpendingList;

View File

@@ -0,0 +1,69 @@
import React from 'react';
import { BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer, Legend } from 'recharts';
import { formatCurrency } from '@/utils/formatters';
interface MonthlyData {
name: string;
budget: number;
expense: number;
}
interface MonthlyComparisonChartProps {
monthlyData: MonthlyData[];
isEmpty?: boolean;
}
const MonthlyComparisonChart: React.FC<MonthlyComparisonChartProps> = ({
monthlyData,
isEmpty = false
}) => {
// Format for Y-axis (K format)
const formatYAxisTick = (value: number) => {
return `${Math.round(value / 1000)}K`;
};
// Format for tooltip (original currency format)
const formatTooltip = (value: number | string) => {
if (typeof value === 'number') {
return formatCurrency(value);
}
return value;
};
// Empty state component
const EmptyGraphState = () => (
<div className="flex flex-col items-center justify-center h-48 text-gray-400">
<p> </p>
<p className="text-sm mt-2"> </p>
</div>
);
return (
<div className="neuro-card h-72">
{!isEmpty && monthlyData.length > 0 ? (
<ResponsiveContainer width="100%" height="100%">
<BarChart data={monthlyData} margin={{
top: 20,
right: 10,
left: -10,
bottom: 5
}} style={{
fontSize: '11px'
}}>
<XAxis dataKey="name" />
<YAxis tickFormatter={formatYAxisTick} />
<Tooltip formatter={formatTooltip} />
<Legend />
<Bar dataKey="budget" name="예산" fill="#C8C8C9" radius={[4, 4, 0, 0]} />
<Bar dataKey="expense" name="지출" fill="#81c784" radius={[4, 4, 0, 0]} />
</BarChart>
</ResponsiveContainer>
) : (
<EmptyGraphState />
)}
</div>
);
};
export default MonthlyComparisonChart;

View File

@@ -0,0 +1,39 @@
import React from 'react';
import { ChevronLeft, ChevronRight } from 'lucide-react';
interface PeriodSelectorProps {
selectedPeriod: string;
onPrevPeriod: () => void;
onNextPeriod: () => void;
}
const PeriodSelector: React.FC<PeriodSelectorProps> = ({
selectedPeriod,
onPrevPeriod,
onNextPeriod
}) => {
return (
<div className="flex items-center justify-between mb-6">
<button
className="neuro-flat p-2 rounded-full"
onClick={onPrevPeriod}
>
<ChevronLeft size={20} />
</button>
<div className="flex items-center">
<span className="font-medium text-lg">{selectedPeriod}</span>
</div>
<button
className="neuro-flat p-2 rounded-full"
onClick={onNextPeriod}
>
<ChevronRight size={20} />
</button>
</div>
);
};
export default PeriodSelector;

View File

@@ -0,0 +1,50 @@
import React from 'react';
import { Wallet, CreditCard, PiggyBank } from 'lucide-react';
import { formatCurrency } from '@/utils/formatters';
interface SummaryCardsProps {
totalBudget: number;
totalExpense: number;
savingsPercentage: number;
}
const SummaryCards: React.FC<SummaryCardsProps> = ({
totalBudget,
totalExpense,
savingsPercentage
}) => {
return (
<div className="grid grid-cols-3 gap-3 mb-8">
<div className="neuro-card">
<div className="flex items-center gap-2 mb-1 py-[5px]">
<Wallet size={24} className="text-gray-500" />
<p className="text-gray-500 text-base"></p>
</div>
<p className="text-sm font-bold text-neuro-income">
{formatCurrency(totalBudget)}
</p>
</div>
<div className="neuro-card">
<div className="flex items-center gap-2 mb-1 py-[5px]">
<CreditCard size={24} className="text-gray-500" />
<p className="text-gray-500 font-medium text-base"></p>
</div>
<p className="text-sm font-bold text-neuro-income">
{formatCurrency(totalExpense)}
</p>
</div>
<div className="neuro-card">
<div className="flex items-center gap-2 mb-1 py-[5px]">
<PiggyBank size={24} className="text-gray-500" />
<p className="text-gray-500 text-base"></p>
</div>
<p className="text-sm font-bold text-neuro-income">
{savingsPercentage}%
</p>
</div>
</div>
);
};
export default SummaryCards;

View File

@@ -3,14 +3,16 @@ import React, { useState, useEffect } from 'react';
import NavBar from '@/components/NavBar';
import ExpenseChart from '@/components/ExpenseChart';
import AddTransactionButton from '@/components/AddTransactionButton';
import { BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer, Legend } from 'recharts';
import { ChevronLeft, ChevronRight, Wallet, CreditCard, PiggyBank } from 'lucide-react';
import { useBudget } from '@/contexts/BudgetContext';
import { formatCurrency } from '@/utils/formatters';
import { EXPENSE_CATEGORIES } from '@/constants/categoryIcons';
import { MONTHS_KR } from '@/hooks/useTransactions';
import { useIsMobile } from '@/hooks/use-mobile';
// 새로 분리한 컴포넌트들 불러오기
import PeriodSelector from '@/components/analytics/PeriodSelector';
import SummaryCards from '@/components/analytics/SummaryCards';
import MonthlyComparisonChart from '@/components/analytics/MonthlyComparisonChart';
import CategorySpendingList from '@/components/analytics/CategorySpendingList';
const Analytics = () => {
const [selectedPeriod, setSelectedPeriod] = useState('이번 달');
const { budgetData, getCategorySpending, transactions } = useBudget();
@@ -22,7 +24,7 @@ const Analytics = () => {
const savings = Math.max(0, totalBudget - totalExpense);
const savingsPercentage = totalBudget > 0 ? Math.round(savings / totalBudget * 100) : 0;
// 카테고리별 지출 차트 데이터 생성 (데이터 초기화 고려)
// 카테고리별 지출 차트 데이터 생성
const categorySpending = getCategorySpending();
const expenseData = categorySpending.map(category => ({
name: category.title,
@@ -32,10 +34,10 @@ const Analytics = () => {
category.title === '교통비' ? '#2E7D32' : '#4CAF50'
}));
// 최근 6개월 데이터를 위한 상태 (빈 데이터로 초기화)
// 최근 6개월 데이터를 위한 상태
const [monthlyData, setMonthlyData] = useState<any[]>([]);
// 월별 데이터 생성 (초기화 로직 개선)
// 월별 데이터 생성
useEffect(() => {
// 현재 월 가져오기
const today = new Date();
@@ -66,38 +68,15 @@ const Analytics = () => {
setMonthlyData(last6Months);
}, [totalBudget, totalExpense]);
// Custom formatter for Y-axis that removes currency symbol and uses K format
const formatYAxisTick = (value: number) => {
return `${Math.round(value / 1000)}K`;
};
// Custom formatter for tooltip that keeps the original formatting with currency symbol
const formatTooltip = (value: number | string) => {
if (typeof value === 'number') {
return formatCurrency(value);
}
return value;
};
// 이전/다음 기간 이동 처리 (현재는 UI만 표시)
// 이전/다음 기간 이동 처리
const handlePrevPeriod = () => {
// 필요에 따라 구현
console.log('이전 기간으로 이동');
};
const handleNextPeriod = () => {
// 필요에 따라 구현
console.log('다음 기간으로 이동');
};
// 그래프 데이터 없을 때 표시할 빈 상태 메시지
const EmptyGraphState = () => (
<div className="flex flex-col items-center justify-center h-48 text-gray-400">
<p> </p>
<p className="text-sm mt-2"> </p>
</div>
);
return (
<div className="min-h-screen bg-neuro-background pb-24">
<div className={`mx-auto px-4 ${isMobile ? 'w-full' : 'max-w-lg'}`}>
@@ -106,87 +85,30 @@ const Analytics = () => {
<h1 className="text-2xl font-bold neuro-text mb-5"> </h1>
{/* Period Selector */}
<div className="flex items-center justify-between mb-6">
<button
className="neuro-flat p-2 rounded-full"
onClick={handlePrevPeriod}
>
<ChevronLeft size={20} />
</button>
<div className="flex items-center">
<span className="font-medium text-lg">{selectedPeriod}</span>
</div>
<button
className="neuro-flat p-2 rounded-full"
onClick={handleNextPeriod}
>
<ChevronRight size={20} />
</button>
</div>
<PeriodSelector
selectedPeriod={selectedPeriod}
onPrevPeriod={handlePrevPeriod}
onNextPeriod={handleNextPeriod}
/>
{/* Summary Cards */}
<div className="grid grid-cols-3 gap-3 mb-8">
<div className="neuro-card">
<div className="flex items-center gap-2 mb-1 py-[5px]">
<Wallet size={24} className="text-gray-500" />
<p className="text-gray-500 text-base"></p>
</div>
<p className="text-sm font-bold text-neuro-income">
{formatCurrency(totalBudget)}
</p>
</div>
<div className="neuro-card">
<div className="flex items-center gap-2 mb-1 py-[5px]">
<CreditCard size={24} className="text-gray-500" />
<p className="text-gray-500 font-medium text-base"></p>
</div>
<p className="text-sm font-bold text-neuro-income">
{formatCurrency(totalExpense)}
</p>
</div>
<div className="neuro-card">
<div className="flex items-center gap-2 mb-1 py-[5px]">
<PiggyBank size={24} className="text-gray-500" />
<p className="text-gray-500 text-base"></p>
</div>
<p className="text-sm font-bold text-neuro-income">
{savingsPercentage}%
</p>
</div>
</div>
<SummaryCards
totalBudget={totalBudget}
totalExpense={totalExpense}
savingsPercentage={savingsPercentage}
/>
</header>
{/* Monthly Comparison - MOVED UP */}
{/* Monthly Comparison Chart */}
<div className="mb-8">
<h2 className="text-lg font-semibold mb-3"> </h2>
<div className="neuro-card h-72">
{monthlyData.length > 0 ? (
<ResponsiveContainer width="100%" height="100%">
<BarChart data={monthlyData} margin={{
top: 20,
right: 10,
left: -10,
bottom: 5
}} style={{
fontSize: '11px'
}}>
<XAxis dataKey="name" />
<YAxis tickFormatter={formatYAxisTick} />
<Tooltip formatter={formatTooltip} />
<Legend />
<Bar dataKey="budget" name="예산" fill="#C8C8C9" radius={[4, 4, 0, 0]} />
<Bar dataKey="expense" name="지출" fill="#81c784" radius={[4, 4, 0, 0]} />
</BarChart>
</ResponsiveContainer>
) : (
<EmptyGraphState />
)}
</div>
<MonthlyComparisonChart
monthlyData={monthlyData}
isEmpty={monthlyData.length === 0}
/>
</div>
{/* Category Pie Chart - MOVED DOWN */}
{/* Category Pie Chart */}
<h2 className="text-lg font-semibold mb-3"> </h2>
{expenseData.some(item => item.value > 0) ? (
<ExpenseChart data={expenseData} />
@@ -198,35 +120,10 @@ const Analytics = () => {
{/* Top Spending Categories */}
<h2 className="text-lg font-semibold mb-3 mt-6"> </h2>
<div className="neuro-card mb-6">
{categorySpending.some(cat => cat.current > 0) ? (
<div className="space-y-4">
{categorySpending.map((category) => (
<div key={category.title} className="flex items-center justify-between">
<div className="flex items-center gap-3">
<div className="w-6 h-6 rounded-full" style={{
backgroundColor: category.title === '식비' ? '#81c784' :
category.title === '생활비' ? '#AED581' : '#2E7D32'
}}></div>
<span>{category.title}</span>
</div>
<div className="text-right">
<p className="font-medium">
{formatCurrency(category.current)}
</p>
<p className="text-xs text-gray-500">
{totalExpense > 0 ? Math.round(category.current / totalExpense * 100) : 0}%
</p>
</div>
</div>
))}
</div>
) : (
<div className="py-8 text-center text-gray-400">
<p> </p>
</div>
)}
</div>
<CategorySpendingList
categories={categorySpending}
totalExpense={totalExpense}
/>
</div>
<AddTransactionButton />