import { Transaction } from '@/components/TransactionCard'; // 트랜잭션 데이터 불러오기 export const loadTransactionsFromStorage = (): Transaction[] => { try { const localData = localStorage.getItem('transactions'); if (localData) { return JSON.parse(localData) as Transaction[]; } // 백업에서 복구 시도 const backupData = localStorage.getItem('transactions_backup'); if (backupData) { console.log('트랜잭션 데이터 백업에서 복구'); localStorage.setItem('transactions', backupData); // 메인 스토리지 복원 return JSON.parse(backupData) as Transaction[]; } } catch (error) { console.error('트랜잭션 데이터 로드 중 오류:', error); } // 데이터가 없을 경우 빈 배열 반환 (샘플 데이터 생성하지 않음) return []; }; // 트랜잭션 데이터 저장하기 export const saveTransactionsToStorage = (transactions: Transaction[]): void => { try { const dataString = JSON.stringify(transactions); localStorage.setItem('transactions', dataString); // 백업 저장 (데이터 손실 방지) localStorage.setItem('transactions_backup', dataString); // 이벤트 발생 window.dispatchEvent(new Event('transactionUpdated')); } catch (error) { console.error('트랜잭션 저장 중 오류:', error); } }; // 예산 불러오기 (이전 버전과의 호환성 유지) export const loadBudgetFromStorage = (): number => { try { // 새 구조의 budgetData 확인 const budgetData = localStorage.getItem('budgetData'); if (budgetData) { const parsedBudgetData = JSON.parse(budgetData); if (parsedBudgetData.monthly && typeof parsedBudgetData.monthly.targetAmount === 'number') { return parsedBudgetData.monthly.targetAmount; } } // 기존 구조 확인 const budget = localStorage.getItem('budget'); if (budget) { const parsedBudget = JSON.parse(budget); return parsedBudget.total || 0; } } catch (error) { console.error('예산 데이터 로드 중 오류:', error); } return 0; }; // 모든 데이터 완전히 초기화 - 성능 최적화 export const resetAllStorageData = (): void => { console.log('완전 초기화 시작 - resetAllStorageData'); try { // 중요: 사용자 설정 값 백업 const dontShowWelcomeValue = localStorage.getItem('dontShowWelcome'); const hasVisitedBefore = localStorage.getItem('hasVisitedBefore'); // 로그인 상태 관련 데이터 백업 const authSession = localStorage.getItem('authSession'); const sbAuth = localStorage.getItem('sb-auth-token'); const supabase = localStorage.getItem('supabase.auth.token'); // 모든 Storage 키 목록 (로그인 관련 항목 제외) const keysToRemove = [ 'transactions', 'budget', 'monthlyExpenses', 'budgetData', 'categoryBudgets', 'analyticData', 'expenseData', 'chartData', 'monthlyData', 'spendingData', 'categorySpending', 'monthlyBudget', 'dailyBudget', 'weeklyBudget', 'monthlyTotals', 'analytics', 'expenseHistory', 'budgetHistory', 'transactionHistory', 'lastSync', 'syncEnabled' ]; // 키 동시에 삭제 (성능 최적화) keysToRemove.forEach(key => { console.log(`삭제 중: ${key}`); localStorage.removeItem(key); localStorage.removeItem(`${key}_backup`); // 백업 키도 함께 삭제 }); // 기본값으로 초기화 - 한번에 처리 const defaultData = { transactions: JSON.stringify([]), budgetData: JSON.stringify({ daily: {targetAmount: 0, spentAmount: 0, remainingAmount: 0}, weekly: {targetAmount: 0, spentAmount: 0, remainingAmount: 0}, monthly: {targetAmount: 0, spentAmount: 0, remainingAmount: 0} }), categoryBudgets: JSON.stringify({ 식비: 0, 교통비: 0, 생활비: 0 }) }; // 모든 기본값 한번에 설정 Object.entries(defaultData).forEach(([key, value]) => { localStorage.setItem(key, value); localStorage.setItem(`${key}_backup`, value); }); // 사용자 설정 값 복원 if (dontShowWelcomeValue) { localStorage.setItem('dontShowWelcome', dontShowWelcomeValue); } if (hasVisitedBefore) { localStorage.setItem('hasVisitedBefore', hasVisitedBefore); } // 로그인 상태 복원 if (authSession) { localStorage.setItem('authSession', authSession); } if (sbAuth) { localStorage.setItem('sb-auth-token', sbAuth); } if (supabase) { localStorage.setItem('supabase.auth.token', supabase); } // 동기화 설정은 무조건 OFF로 설정 localStorage.setItem('syncEnabled', 'false'); console.log('동기화 설정이 OFF로 변경되었습니다'); // 모든 이벤트 한 번에 발생 (성능 최적화) const events = [ new Event('transactionUpdated'), new Event('budgetDataUpdated'), new Event('categoryBudgetsUpdated'), new StorageEvent('storage'), new Event('auth-state-changed') ]; events.forEach(event => window.dispatchEvent(event)); console.log('모든 저장소 데이터가 완전히 초기화되었습니다. (동기화 설정이 OFF로 변경됨)'); } catch (error) { console.error('데이터 초기화 중 오류:', error); } };