Fix data initialization issue

The data initialization logic was not properly clearing existing data, leading to incorrect budget values. This commit ensures that all relevant data is cleared upon initialization.
This commit is contained in:
gpt-engineer-app[bot]
2025-03-15 23:08:06 +00:00
parent f8abebcac6
commit d798632d05
5 changed files with 191 additions and 40 deletions

View File

@@ -1,13 +1,30 @@
import React, { createContext, useContext, ReactNode } from 'react';
import { BudgetContextType } from './types';
import React, { createContext, useContext } from 'react';
import { useBudgetState } from './useBudgetState';
import { BudgetData, BudgetPeriod, Transaction } from './types';
// Context 생성
// 컨텍스트 인터페이스 정의
interface BudgetContextType {
transactions: Transaction[];
selectedTab: BudgetPeriod;
setSelectedTab: (tab: BudgetPeriod) => void;
budgetData: BudgetData;
categoryBudgets: Record<string, number>;
getCategorySpending: () => Array<{
title: string;
current: number;
total: number;
}>;
updateTransaction: (transaction: Transaction) => void;
handleBudgetGoalUpdate: (type: BudgetPeriod, amount: number, newCategoryBudgets?: Record<string, number>) => void;
resetBudgetData?: () => void; // 선택적 필드로 추가
}
// 컨텍스트 생성
const BudgetContext = createContext<BudgetContextType | undefined>(undefined);
// Context Provider 컴포넌트
export const BudgetProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
// 컨텍스트 프로바이더 컴포넌트
export const BudgetProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
const budgetState = useBudgetState();
return (
@@ -17,11 +34,13 @@ export const BudgetProvider: React.FC<{ children: ReactNode }> = ({ children })
);
};
// Context 사용Hook
export const useBudget = () => {
// 컨텍스트 접근
export const useBudget = (): BudgetContextType => {
const context = useContext(BudgetContext);
if (!context) {
if (context === undefined) {
throw new Error('useBudget must be used within a BudgetProvider');
}
return context;
};
export type { BudgetPeriod } from './types';

View File

@@ -92,6 +92,8 @@ export const clearAllBudgetData = (): void => {
// 모든 데이터 초기화 (첫 로그인 상태)
export const resetAllData = (): void => {
console.log('완전 초기화 시작 - resetAllData');
// 모든 관련 데이터 키 목록 (분석 페이지의 데이터 포함)
const dataKeys = [
'transactions',
@@ -104,19 +106,29 @@ export const resetAllData = (): void => {
'expenseAnalytics', // 지출 분석 데이터
'expenseHistory', // 지출 이력
'budgetHistory', // 예산 이력
'analyticsCache' // 분석 캐시 데이터
'analyticsCache', // 분석 캐시 데이터
'monthlyTotals', // 월간 합계 데이터
'analytics', // 분석 페이지 데이터
'dailyBudget', // 일일 예산
'weeklyBudget', // 주간 예산
'monthlyBudget', // 월간 예산
'chartData', // 차트 데이터
'dontShowWelcome' // 환영 메시지 표시 여부
];
// 모든 관련 데이터 키 삭제
dataKeys.forEach(key => localStorage.removeItem(key));
dataKeys.forEach(key => {
console.log(`삭제 중: ${key}`);
localStorage.removeItem(key);
});
// 기본 데이터로 초기화
clearAllTransactions();
clearAllCategoryBudgets();
clearAllBudgetData();
// 추가적으로 사용자 기기에 저장된 모든 데이터 검사
for (let i = 0; i < localStorage.length; i++) {
// 추가적으로 사용자 기기에 저장된 모든 데이터 검사 (역순으로 루프)
for (let i = localStorage.length - 1; i >= 0; i--) {
const key = localStorage.key(i);
if (key && (
key.includes('expense') ||
@@ -124,13 +136,28 @@ export const resetAllData = (): void => {
key.includes('transaction') ||
key.includes('analytics') ||
key.includes('spending') ||
key.includes('financial')
key.includes('financial') ||
key.includes('chart') ||
key.includes('month') ||
key.includes('sync') ||
key.includes('total') ||
key.includes('welcome') ||
key.includes('visited')
)) {
console.log(`추가 데이터 삭제: ${key}`);
localStorage.removeItem(key);
}
}
// 강제로 빈 데이터로 초기화
localStorage.setItem('transactions', JSON.stringify([]));
localStorage.setItem('budget', JSON.stringify({total: 0}));
localStorage.setItem('budgetData', JSON.stringify({
daily: {targetAmount: 0, spentAmount: 0, remainingAmount: 0},
weekly: {targetAmount: 0, spentAmount: 0, remainingAmount: 0},
monthly: {targetAmount: 0, spentAmount: 0, remainingAmount: 0}
}));
localStorage.setItem('categoryBudgets', JSON.stringify(DEFAULT_CATEGORY_BUDGETS));
console.log('모든 데이터가 초기화되었습니다.');
};

View File

@@ -1,5 +1,5 @@
import { useState, useEffect } from 'react';
import { useState, useEffect, useCallback } from 'react';
import { BudgetData, BudgetPeriod, Transaction } from './types';
import { toast } from '@/components/ui/use-toast';
import {
@@ -8,7 +8,10 @@ import {
loadCategoryBudgetsFromStorage,
saveCategoryBudgetsToStorage,
loadBudgetDataFromStorage,
saveBudgetDataToStorage
saveBudgetDataToStorage,
clearAllTransactions,
clearAllCategoryBudgets,
clearAllBudgetData
} from './storageUtils';
import {
calculateCategorySpending,
@@ -23,6 +26,23 @@ export const useBudgetState = () => {
const [categoryBudgets, setCategoryBudgets] = useState<Record<string, number>>(loadCategoryBudgetsFromStorage());
const [budgetData, setBudgetData] = useState<BudgetData>(loadBudgetDataFromStorage());
// 데이터 리셋 함수
const resetBudgetData = useCallback(() => {
console.log('BudgetContext에서 데이터 리셋 시작');
// 로컬 스토리지 초기화
clearAllTransactions();
clearAllCategoryBudgets();
clearAllBudgetData();
// 메모리내 상태 초기화
setTransactions([]);
setCategoryBudgets(loadCategoryBudgetsFromStorage());
setBudgetData(loadBudgetDataFromStorage());
console.log('BudgetContext에서 데이터 리셋 완료');
}, []);
// 트랜잭션 로드
useEffect(() => {
const loadTransactions = () => {
@@ -93,7 +113,7 @@ export const useBudgetState = () => {
// 월간 예산을 업데이트하고 일일, 주간도 자동 계산
if (type === 'monthly') {
const ratio = amount / budgetData.monthly.targetAmount;
const ratio = amount / (budgetData.monthly.targetAmount || 1); // 0으로 나누기 방지
const updatedCategoryBudgets: Record<string, number> = {};
Object.keys(categoryBudgets).forEach(category => {
@@ -133,6 +153,7 @@ export const useBudgetState = () => {
setSelectedTab,
updateTransaction,
handleBudgetGoalUpdate,
getCategorySpending
getCategorySpending,
resetBudgetData // 새로 추가된 리셋 함수
};
};