From f8abebcac6ee9ac59dce4d714a593cf0fafb399e Mon Sep 17 00:00:00 2001 From: "gpt-engineer-app[bot]" <159125892+gpt-engineer-app[bot]@users.noreply.github.com> Date: Sat, 15 Mar 2025 23:03:44 +0000 Subject: [PATCH] Clear persistent budget data Clear persistent budget data to ensure a clean state. --- src/contexts/budget/budgetUtils.ts | 22 +++--- src/pages/Analytics.tsx | 121 ++++++++++++++++++----------- src/pages/Index.tsx | 57 +++++++++++--- src/utils/storageUtils.ts | 44 ++++++++--- 4 files changed, 166 insertions(+), 78 deletions(-) diff --git a/src/contexts/budget/budgetUtils.ts b/src/contexts/budget/budgetUtils.ts index 31f304e..f810125 100644 --- a/src/contexts/budget/budgetUtils.ts +++ b/src/contexts/budget/budgetUtils.ts @@ -2,14 +2,14 @@ import { BudgetData, BudgetPeriod, CategoryBudget, Transaction } from './types'; import { EXPENSE_CATEGORIES } from '@/constants/categoryIcons'; -// 기본 데이터 상수 +// 기본 데이터 상수 (기본값을 0으로 변경) export const DEFAULT_CATEGORY_BUDGETS: Record = { - 식비: 400000, - 생활비: 600000, - 교통비: 200000 + 식비: 0, + 생활비: 0, + 교통비: 0 }; -export const DEFAULT_MONTHLY_BUDGET = 1200000; +export const DEFAULT_MONTHLY_BUDGET = 0; // 카테고리별 지출 계산 export const calculateCategorySpending = ( @@ -126,19 +126,19 @@ export const calculateSpentAmounts = ( export const getInitialBudgetData = (): BudgetData => { return { daily: { - targetAmount: Math.round(DEFAULT_MONTHLY_BUDGET / 30), + targetAmount: 0, spentAmount: 0, - remainingAmount: Math.round(DEFAULT_MONTHLY_BUDGET / 30) + remainingAmount: 0 }, weekly: { - targetAmount: Math.round(DEFAULT_MONTHLY_BUDGET / 4.3), + targetAmount: 0, spentAmount: 0, - remainingAmount: Math.round(DEFAULT_MONTHLY_BUDGET / 4.3) + remainingAmount: 0 }, monthly: { - targetAmount: DEFAULT_MONTHLY_BUDGET, + targetAmount: 0, spentAmount: 0, - remainingAmount: DEFAULT_MONTHLY_BUDGET + remainingAmount: 0 } }; }; diff --git a/src/pages/Analytics.tsx b/src/pages/Analytics.tsx index 8dd8183..1eff66d 100644 --- a/src/pages/Analytics.tsx +++ b/src/pages/Analytics.tsx @@ -20,7 +20,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, @@ -30,30 +30,33 @@ const Analytics = () => { category.title === '교통비' ? '#2E7D32' : '#4CAF50' })); - // 최근 6개월 데이터를 위한 상태 + // 최근 6개월 데이터를 위한 상태 (빈 데이터로 초기화) const [monthlyData, setMonthlyData] = useState([]); - // 월별 데이터 생성 (실제 데이터 + 예상 데이터) + // 월별 데이터 생성 (초기화 로직 개선) useEffect(() => { // 현재 월 가져오기 const today = new Date(); const currentMonth = today.getMonth(); + if (totalBudget === 0 && totalExpense === 0) { + // 모든 데이터가 초기화된 상태라면 빈 배열 사용 + setMonthlyData([]); + return; + } + // 최근 6개월 데이터 배열 생성 const last6Months = []; for (let i = 5; i >= 0; i--) { const monthIndex = (currentMonth - i + 12) % 12; // 순환적으로 이전 월 계산 const month = MONTHS_KR[monthIndex]; // 월 이름 가져오기 - // 현재 달은 실제 데이터 사용, 이전 달은 예상 데이터 사용 - const isCurrentMonth = i === 0; - const expense = isCurrentMonth - ? totalExpense - : totalBudget * (0.5 + Math.random() * 0.3); // 예상 데이터 (총 예산의 50~80%) + // 현재 달은 실제 데이터 사용, 다른 달은 0으로 설정 + const expense = i === 0 ? totalExpense : 0; last6Months.push({ name: month.split(' ')[0], // '8월' 형식으로 변환 - budget: totalBudget, + budget: i === 0 ? totalBudget : 0, expense: expense }); } @@ -85,6 +88,14 @@ const Analytics = () => { console.log('다음 기간으로 이동'); }; + // 그래프 데이터 없을 때 표시할 빈 상태 메시지 + const EmptyGraphState = () => ( +
+

데이터가 없습니다

+

지출 내역을 추가하면 그래프가 표시됩니다

+
+ ); + return (
@@ -149,54 +160,70 @@ const Analytics = () => {

월별 그래프

- - - - - - - - - - + {monthlyData.length > 0 ? ( + + + + + + + + + + + ) : ( + + )}
{/* Category Pie Chart - MOVED DOWN */}

카테고리별 지출

- + {expenseData.some(item => item.value > 0) ? ( + + ) : ( +
+

데이터가 없습니다

+
+ )} {/* Top Spending Categories */}

주요 지출 카테고리

-
- {categorySpending.map((category) => ( -
-
-
- {category.title} + {categorySpending.some(cat => cat.current > 0) ? ( +
+ {categorySpending.map((category) => ( +
+
+
+ {category.title} +
+
+

+ {formatCurrency(category.current)} +

+

+ {totalExpense > 0 ? Math.round(category.current / totalExpense * 100) : 0}% +

+
-
-

- {formatCurrency(category.current)} -

-

- {totalExpense > 0 ? Math.round(category.current / totalExpense * 100) : 0}% -

-
-
- ))} -
+ ))} +
+ ) : ( +
+

아직 지출 내역이 없습니다

+
+ )}
diff --git a/src/pages/Index.tsx b/src/pages/Index.tsx index e904d3a..b39dc2d 100644 --- a/src/pages/Index.tsx +++ b/src/pages/Index.tsx @@ -27,14 +27,32 @@ const Index = () => { const { user } = useAuth(); const [showWelcome, setShowWelcome] = useState(false); + const [isInitialized, setIsInitialized] = useState(false); // 화면이 처음 로드될 때 데이터 초기화 useEffect(() => { - // 데이터를 완전히 초기화 (두 가지 초기화 함수 모두 호출) - resetAllData(); - resetAllStorageData(); + if (!isInitialized) { + // 모든 데이터 완전히 삭제 및 초기화 (두 가지 초기화 함수 모두 반복 호출) + resetAllData(); + resetAllStorageData(); + resetAllData(); // 한번 더 실행해서 확실히 지움 + + // localStorage 직접 초기화 (추가 보호) + localStorage.removeItem('budget'); + localStorage.removeItem('budgetData'); + localStorage.removeItem('categoryBudgets'); + localStorage.removeItem('transactions'); + localStorage.removeItem('monthlyExpenses'); + localStorage.removeItem('monthlyData'); + + // 데이터를 비운 후 빈 값 저장 + localStorage.setItem('transactions', JSON.stringify([])); + + setIsInitialized(true); + console.log('모든 데이터 초기화 완료'); + } - // 환영 다이얼로그 표시 여부 결정 + // 환영 다이얼로그 표시 여부 결정 (데이터 초기화 후) const dontShowWelcome = localStorage.getItem('dontShowWelcome') === 'true'; if (!dontShowWelcome) { setShowWelcome(true); @@ -42,7 +60,7 @@ const Index = () => { // 방문 기록 저장 (초기화 후에 저장) localStorage.setItem('hasVisitedBefore', 'true'); - }, []); + }, [isInitialized]); // 환영 팝업 닫기 const handleCloseWelcome = (dontShowAgain: boolean) => { @@ -52,6 +70,14 @@ const Index = () => { } }; + // 빈 데이터 상태 메시지 + const EmptyState = () => ( +
+

아직 데이터가 없습니다

+

예산을 설정하고 지출을 추가해 보세요

+
+ ); + return (
@@ -69,13 +95,24 @@ const Index = () => { /> {/* 지출 카테고리 */} - + {getCategorySpending().some(cat => cat.current > 0 || cat.total > 0) ? ( + + ) : ( + + )} {/* 최근 지출 */} - + {transactions.length > 0 ? ( + + ) : ( +
+

최근 지출

+ +
+ )}
diff --git a/src/utils/storageUtils.ts b/src/utils/storageUtils.ts index 695acda..4b82582 100644 --- a/src/utils/storageUtils.ts +++ b/src/utils/storageUtils.ts @@ -26,23 +26,47 @@ export const loadBudgetFromStorage = (): number => { const budgetData = localStorage.getItem('budget'); if (budgetData) { const parsedBudget = JSON.parse(budgetData); - return parsedBudget.total || 1000000; + return parsedBudget.total || 0; // 기본값을 0으로 변경 } - return 1000000; // 기본 예산 + return 0; // 기본값 0으로 변경 }; // 모든 데이터 완전히 초기화 export const resetAllStorageData = (): void => { - // 트랜잭션 초기화 - localStorage.removeItem('transactions'); + // 모든 Storage 키 삭제 + const keysToRemove = [ + 'transactions', + 'budget', + 'monthlyExpenses', + 'budgetData', + 'categoryBudgets', + 'analyticData', + 'expenseData', + 'chartData', + 'monthlyData', + 'spendingData' + ]; + + // 명시적으로 알려진 키들 삭제 + keysToRemove.forEach(key => localStorage.removeItem(key)); + + // 명시적으로 트랜잭션 초기화 localStorage.setItem('transactions', JSON.stringify([])); - // 월별 지출 데이터 초기화 - localStorage.removeItem('monthlyExpenses'); + // 모든 예산 관련, 지출 관련 데이터 검색 및 삭제 + const keywordsToFind = ['budget', 'expense', 'transaction', 'analytic', 'spending', 'chart', 'financial', 'money', 'category']; - // 예산 초기화 - localStorage.removeItem('budget'); + // 모든 localStorage 순회하며 키워드 포함된 항목 삭제 + for (let i = 0; i < localStorage.length; i++) { + const key = localStorage.key(i); + if (key) { + const lowerKey = key.toLowerCase(); + if (keywordsToFind.some(keyword => lowerKey.includes(keyword))) { + console.log(`추가 데이터 삭제: ${key}`); + localStorage.removeItem(key); + } + } + } - console.log('모든 저장소 데이터가 초기화되었습니다.'); + console.log('모든 저장소 데이터가 완전히 초기화되었습니다.'); }; -