Refactor budget storage utils
Splits the budget storage utils file into smaller, more manageable files for better organization and maintainability.
This commit is contained in:
@@ -4,7 +4,7 @@ import {
|
||||
loadCategoryBudgetsFromStorage,
|
||||
saveCategoryBudgetsToStorage,
|
||||
clearAllCategoryBudgets
|
||||
} from '../storageUtils';
|
||||
} from '../storage/categoryStorage';
|
||||
|
||||
// 카테고리 예산 상태 관리 훅
|
||||
export const useCategoryBudgetState = () => {
|
||||
|
||||
52
src/contexts/budget/storage/budgetStorage.ts
Normal file
52
src/contexts/budget/storage/budgetStorage.ts
Normal file
@@ -0,0 +1,52 @@
|
||||
|
||||
import { BudgetData } from '../types';
|
||||
import { getInitialBudgetData } from '../budgetUtils';
|
||||
|
||||
/**
|
||||
* 예산 데이터 불러오기
|
||||
*/
|
||||
export const loadBudgetDataFromStorage = (): BudgetData => {
|
||||
try {
|
||||
const storedBudgetData = localStorage.getItem('budgetData');
|
||||
if (storedBudgetData) {
|
||||
const parsed = JSON.parse(storedBudgetData);
|
||||
console.log('예산 데이터 로드 완료');
|
||||
return parsed;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('예산 데이터 파싱 오류:', error);
|
||||
}
|
||||
|
||||
// 새 사용자를 위한 기본 예산 데이터 저장
|
||||
console.log('기본 예산 데이터 설정');
|
||||
const initialData = getInitialBudgetData();
|
||||
saveBudgetDataToStorage(initialData);
|
||||
return initialData;
|
||||
};
|
||||
|
||||
/**
|
||||
* 예산 데이터 저장
|
||||
*/
|
||||
export const saveBudgetDataToStorage = (budgetData: BudgetData): void => {
|
||||
try {
|
||||
localStorage.setItem('budgetData', JSON.stringify(budgetData));
|
||||
console.log('예산 데이터 저장 완료');
|
||||
} catch (error) {
|
||||
console.error('예산 데이터 저장 오류:', error);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 모든 예산 데이터 삭제
|
||||
*/
|
||||
export const clearAllBudgetData = (): void => {
|
||||
try {
|
||||
localStorage.removeItem('budgetData');
|
||||
// 기본값으로 재설정
|
||||
const initialData = getInitialBudgetData();
|
||||
saveBudgetDataToStorage(initialData);
|
||||
console.log('예산 데이터가 초기화되었습니다.');
|
||||
} catch (error) {
|
||||
console.error('예산 데이터 삭제 오류:', error);
|
||||
}
|
||||
};
|
||||
49
src/contexts/budget/storage/categoryStorage.ts
Normal file
49
src/contexts/budget/storage/categoryStorage.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
|
||||
import { DEFAULT_CATEGORY_BUDGETS } from '../budgetUtils';
|
||||
|
||||
/**
|
||||
* 카테고리 예산 불러오기
|
||||
*/
|
||||
export const loadCategoryBudgetsFromStorage = (): Record<string, number> => {
|
||||
try {
|
||||
const storedCategoryBudgets = localStorage.getItem('categoryBudgets');
|
||||
if (storedCategoryBudgets) {
|
||||
const parsed = JSON.parse(storedCategoryBudgets);
|
||||
console.log('카테고리 예산 로드 완료:', parsed);
|
||||
return parsed;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('카테고리 예산 데이터 파싱 오류:', error);
|
||||
}
|
||||
|
||||
// 새 사용자를 위한 기본 카테고리 예산 저장
|
||||
console.log('기본 카테고리 예산 설정');
|
||||
saveCategoryBudgetsToStorage(DEFAULT_CATEGORY_BUDGETS);
|
||||
return DEFAULT_CATEGORY_BUDGETS;
|
||||
};
|
||||
|
||||
/**
|
||||
* 카테고리 예산 저장
|
||||
*/
|
||||
export const saveCategoryBudgetsToStorage = (categoryBudgets: Record<string, number>): void => {
|
||||
try {
|
||||
localStorage.setItem('categoryBudgets', JSON.stringify(categoryBudgets));
|
||||
console.log('카테고리 예산 저장 완료:', categoryBudgets);
|
||||
} catch (error) {
|
||||
console.error('카테고리 예산 저장 오류:', error);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 모든 카테고리 예산 삭제
|
||||
*/
|
||||
export const clearAllCategoryBudgets = (): void => {
|
||||
try {
|
||||
localStorage.removeItem('categoryBudgets');
|
||||
// 기본값으로 재설정
|
||||
saveCategoryBudgetsToStorage(DEFAULT_CATEGORY_BUDGETS);
|
||||
console.log('카테고리 예산이 초기화되었습니다.');
|
||||
} catch (error) {
|
||||
console.error('카테고리 예산 삭제 오류:', error);
|
||||
}
|
||||
};
|
||||
26
src/contexts/budget/storage/index.ts
Normal file
26
src/contexts/budget/storage/index.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
|
||||
// 트랜잭션 관련 함수 내보내기
|
||||
export {
|
||||
loadTransactionsFromStorage,
|
||||
saveTransactionsToStorage,
|
||||
clearAllTransactions
|
||||
} from './transactionStorage';
|
||||
|
||||
// 예산 데이터 관련 함수 내보내기
|
||||
export {
|
||||
loadBudgetDataFromStorage,
|
||||
saveBudgetDataToStorage,
|
||||
clearAllBudgetData
|
||||
} from './budgetStorage';
|
||||
|
||||
// 카테고리 관련 함수 내보내기
|
||||
export {
|
||||
loadCategoryBudgetsFromStorage,
|
||||
saveCategoryBudgetsToStorage,
|
||||
clearAllCategoryBudgets
|
||||
} from './categoryStorage';
|
||||
|
||||
// 데이터 초기화 함수 내보내기
|
||||
export {
|
||||
resetAllData
|
||||
} from './resetStorage';
|
||||
93
src/contexts/budget/storage/resetStorage.ts
Normal file
93
src/contexts/budget/storage/resetStorage.ts
Normal file
@@ -0,0 +1,93 @@
|
||||
|
||||
import { clearAllTransactions } from './transactionStorage';
|
||||
import { clearAllCategoryBudgets } from './categoryStorage';
|
||||
import { clearAllBudgetData } from './budgetStorage';
|
||||
import { DEFAULT_CATEGORY_BUDGETS } from '../budgetUtils';
|
||||
import { getInitialBudgetData } from '../budgetUtils';
|
||||
|
||||
/**
|
||||
* 모든 데이터 초기화 (첫 로그인 상태)
|
||||
*/
|
||||
export const resetAllData = (): void => {
|
||||
console.log('완전 초기화 시작 - resetAllData');
|
||||
|
||||
// dontShowWelcome 설정 값 백업
|
||||
const dontShowWelcomeValue = localStorage.getItem('dontShowWelcome');
|
||||
console.log('resetAllData - dontShowWelcome 백업 값:', dontShowWelcomeValue);
|
||||
|
||||
// 모든 관련 데이터 키 목록 (분석 페이지의 데이터 포함)
|
||||
const dataKeys = [
|
||||
'transactions',
|
||||
'categoryBudgets',
|
||||
'budgetData',
|
||||
'budget',
|
||||
'hasVisitedBefore',
|
||||
'monthlyExpenses', // 월간 지출 데이터
|
||||
'categorySpending', // 카테고리별 지출 데이터
|
||||
'expenseAnalytics', // 지출 분석 데이터
|
||||
'expenseHistory', // 지출 이력
|
||||
'budgetHistory', // 예산 이력
|
||||
'analyticsCache', // 분석 캐시 데이터
|
||||
'monthlyTotals', // 월간 합계 데이터
|
||||
'analytics', // 분석 페이지 데이터
|
||||
'dailyBudget', // 일일 예산
|
||||
'weeklyBudget', // 주간 예산
|
||||
'monthlyBudget', // 월간 예산
|
||||
'chartData', // 차트 데이터
|
||||
// 'dontShowWelcome' 키는 삭제 목록에서 제외
|
||||
];
|
||||
|
||||
// 모든 관련 데이터 키 삭제
|
||||
dataKeys.forEach(key => {
|
||||
console.log(`삭제 중: ${key}`);
|
||||
localStorage.removeItem(key);
|
||||
});
|
||||
|
||||
// 기본 데이터로 초기화
|
||||
clearAllTransactions();
|
||||
clearAllCategoryBudgets();
|
||||
clearAllBudgetData();
|
||||
|
||||
// 추가적으로 사용자 기기에 저장된 모든 데이터 검사 (역순으로 루프)
|
||||
for (let i = localStorage.length - 1; i >= 0; i--) {
|
||||
const key = localStorage.key(i);
|
||||
if (key && key !== 'dontShowWelcome' && ( // dontShowWelcome 키는 제외
|
||||
key.includes('expense') ||
|
||||
key.includes('budget') ||
|
||||
key.includes('transaction') ||
|
||||
key.includes('analytics') ||
|
||||
key.includes('spending') ||
|
||||
key.includes('financial') ||
|
||||
key.includes('chart') ||
|
||||
key.includes('month') ||
|
||||
key.includes('sync') ||
|
||||
key.includes('total') ||
|
||||
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));
|
||||
|
||||
// dontShowWelcome 값 복원 (백업한 값이 있는 경우)
|
||||
if (dontShowWelcomeValue) {
|
||||
console.log('resetAllData - dontShowWelcome 값 복원:', dontShowWelcomeValue);
|
||||
localStorage.setItem('dontShowWelcome', dontShowWelcomeValue);
|
||||
|
||||
// 복원 확인
|
||||
const restoredValue = localStorage.getItem('dontShowWelcome');
|
||||
console.log('resetAllData - 복원 후 dontShowWelcome 값:', restoredValue);
|
||||
}
|
||||
|
||||
console.log('모든 데이터가 초기화되었습니다.');
|
||||
};
|
||||
43
src/contexts/budget/storage/transactionStorage.ts
Normal file
43
src/contexts/budget/storage/transactionStorage.ts
Normal file
@@ -0,0 +1,43 @@
|
||||
|
||||
import { Transaction } from '../types';
|
||||
|
||||
/**
|
||||
* 로컬 스토리지에서 트랜잭션 불러오기
|
||||
*/
|
||||
export const loadTransactionsFromStorage = (): Transaction[] => {
|
||||
try {
|
||||
const storedTransactions = localStorage.getItem('transactions');
|
||||
if (storedTransactions) {
|
||||
return JSON.parse(storedTransactions);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('트랜잭션 데이터 파싱 오류:', error);
|
||||
}
|
||||
return [];
|
||||
};
|
||||
|
||||
/**
|
||||
* 트랜잭션 저장
|
||||
*/
|
||||
export const saveTransactionsToStorage = (transactions: Transaction[]): void => {
|
||||
try {
|
||||
localStorage.setItem('transactions', JSON.stringify(transactions));
|
||||
console.log('트랜잭션 저장 완료, 항목 수:', transactions.length);
|
||||
} catch (error) {
|
||||
console.error('트랜잭션 저장 오류:', error);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 모든 트랜잭션 삭제
|
||||
*/
|
||||
export const clearAllTransactions = (): void => {
|
||||
try {
|
||||
localStorage.removeItem('transactions');
|
||||
// 빈 배열을 저장하여 확실히 초기화
|
||||
localStorage.setItem('transactions', JSON.stringify([]));
|
||||
console.log('모든 트랜잭션이 삭제되었습니다.');
|
||||
} catch (error) {
|
||||
console.error('트랜잭션 삭제 오류:', error);
|
||||
}
|
||||
};
|
||||
@@ -1,206 +1,23 @@
|
||||
import { BudgetData, Transaction } from './types';
|
||||
import { DEFAULT_CATEGORY_BUDGETS, getInitialBudgetData } from './budgetUtils';
|
||||
|
||||
// 로컬 스토리지에서 트랜잭션 불러오기
|
||||
export const loadTransactionsFromStorage = (): Transaction[] => {
|
||||
try {
|
||||
const storedTransactions = localStorage.getItem('transactions');
|
||||
if (storedTransactions) {
|
||||
return JSON.parse(storedTransactions);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('트랜잭션 데이터 파싱 오류:', error);
|
||||
}
|
||||
return [];
|
||||
};
|
||||
// 외부 파일로 리팩토링된 모든 스토리지 관련 함수를 통합적으로 내보내는 파일
|
||||
// 기존 코드는 storage/ 디렉터리로 이동되었습니다.
|
||||
|
||||
// 트랜잭션 저장
|
||||
export const saveTransactionsToStorage = (transactions: Transaction[]): void => {
|
||||
try {
|
||||
localStorage.setItem('transactions', JSON.stringify(transactions));
|
||||
console.log('트랜잭션 저장 완료, 항목 수:', transactions.length);
|
||||
} catch (error) {
|
||||
console.error('트랜잭션 저장 오류:', error);
|
||||
}
|
||||
};
|
||||
|
||||
// 모든 트랜잭션 삭제
|
||||
export const clearAllTransactions = (): void => {
|
||||
try {
|
||||
localStorage.removeItem('transactions');
|
||||
// 빈 배열을 저장하여 확실히 초기화
|
||||
localStorage.setItem('transactions', JSON.stringify([]));
|
||||
console.log('모든 트랜잭션이 삭제되었습니다.');
|
||||
} catch (error) {
|
||||
console.error('트랜잭션 삭제 오류:', error);
|
||||
}
|
||||
};
|
||||
|
||||
// 카테고리 예산 불러오기
|
||||
export const loadCategoryBudgetsFromStorage = (): Record<string, number> => {
|
||||
try {
|
||||
const storedCategoryBudgets = localStorage.getItem('categoryBudgets');
|
||||
if (storedCategoryBudgets) {
|
||||
const parsed = JSON.parse(storedCategoryBudgets);
|
||||
console.log('카테고리 예산 로드 완료:', parsed);
|
||||
return parsed;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('카테고리 예산 데이터 파싱 오류:', error);
|
||||
}
|
||||
export {
|
||||
// 트랜잭션 관련 함수
|
||||
loadTransactionsFromStorage,
|
||||
saveTransactionsToStorage,
|
||||
clearAllTransactions,
|
||||
|
||||
// 새 사용자를 위한 기본 카테고리 예산 저장
|
||||
console.log('기본 카테고리 예산 설정');
|
||||
saveCategoryBudgetsToStorage(DEFAULT_CATEGORY_BUDGETS);
|
||||
return DEFAULT_CATEGORY_BUDGETS;
|
||||
};
|
||||
|
||||
// 카테고리 예산 저장
|
||||
export const saveCategoryBudgetsToStorage = (categoryBudgets: Record<string, number>): void => {
|
||||
try {
|
||||
localStorage.setItem('categoryBudgets', JSON.stringify(categoryBudgets));
|
||||
console.log('카테고리 예산 저장 완료:', categoryBudgets);
|
||||
} catch (error) {
|
||||
console.error('카테고리 예산 저장 오류:', error);
|
||||
}
|
||||
};
|
||||
|
||||
// 모든 카테고리 예산 삭제
|
||||
export const clearAllCategoryBudgets = (): void => {
|
||||
try {
|
||||
localStorage.removeItem('categoryBudgets');
|
||||
// 기본값으로 재설정
|
||||
saveCategoryBudgetsToStorage(DEFAULT_CATEGORY_BUDGETS);
|
||||
console.log('카테고리 예산이 초기화되었습니다.');
|
||||
} catch (error) {
|
||||
console.error('카테고리 예산 삭제 오류:', error);
|
||||
}
|
||||
};
|
||||
|
||||
// 예산 데이터 불러오기
|
||||
export const loadBudgetDataFromStorage = (): BudgetData => {
|
||||
try {
|
||||
const storedBudgetData = localStorage.getItem('budgetData');
|
||||
if (storedBudgetData) {
|
||||
const parsed = JSON.parse(storedBudgetData);
|
||||
console.log('예산 데이터 로드 완료');
|
||||
return parsed;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('예산 데이터 파싱 오류:', error);
|
||||
}
|
||||
// 예산 데이터 관련 함수
|
||||
loadBudgetDataFromStorage,
|
||||
saveBudgetDataToStorage,
|
||||
clearAllBudgetData,
|
||||
|
||||
// 새 사용자를 위한 기본 예산 데이터 저장
|
||||
console.log('기본 예산 데이터 설정');
|
||||
const initialData = getInitialBudgetData();
|
||||
saveBudgetDataToStorage(initialData);
|
||||
return initialData;
|
||||
};
|
||||
|
||||
// 예산 데이터 저장
|
||||
export const saveBudgetDataToStorage = (budgetData: BudgetData): void => {
|
||||
try {
|
||||
localStorage.setItem('budgetData', JSON.stringify(budgetData));
|
||||
console.log('예산 데이터 저장 완료');
|
||||
} catch (error) {
|
||||
console.error('예산 데이터 저장 오류:', error);
|
||||
}
|
||||
};
|
||||
|
||||
// 모든 예산 데이터 삭제
|
||||
export const clearAllBudgetData = (): void => {
|
||||
try {
|
||||
localStorage.removeItem('budgetData');
|
||||
// 기본값으로 재설정
|
||||
const initialData = getInitialBudgetData();
|
||||
saveBudgetDataToStorage(initialData);
|
||||
console.log('예산 데이터가 초기화되었습니다.');
|
||||
} catch (error) {
|
||||
console.error('예산 데이터 삭제 오류:', error);
|
||||
}
|
||||
};
|
||||
|
||||
// 모든 데이터 초기화 (첫 로그인 상태)
|
||||
export const resetAllData = (): void => {
|
||||
console.log('완전 초기화 시작 - resetAllData');
|
||||
// 카테고리 관련 함수
|
||||
loadCategoryBudgetsFromStorage,
|
||||
saveCategoryBudgetsToStorage,
|
||||
clearAllCategoryBudgets,
|
||||
|
||||
// dontShowWelcome 설정 값 백업
|
||||
const dontShowWelcomeValue = localStorage.getItem('dontShowWelcome');
|
||||
console.log('resetAllData - dontShowWelcome 백업 값:', dontShowWelcomeValue);
|
||||
|
||||
// 모든 관련 데이터 키 목록 (분석 페이지의 데이터 포함)
|
||||
const dataKeys = [
|
||||
'transactions',
|
||||
'categoryBudgets',
|
||||
'budgetData',
|
||||
'budget',
|
||||
'hasVisitedBefore',
|
||||
'monthlyExpenses', // 월간 지출 데이터
|
||||
'categorySpending', // 카테고리별 지출 데이터
|
||||
'expenseAnalytics', // 지출 분석 데이터
|
||||
'expenseHistory', // 지출 이력
|
||||
'budgetHistory', // 예산 이력
|
||||
'analyticsCache', // 분석 캐시 데이터
|
||||
'monthlyTotals', // 월간 합계 데이터
|
||||
'analytics', // 분석 페이지 데이터
|
||||
'dailyBudget', // 일일 예산
|
||||
'weeklyBudget', // 주간 예산
|
||||
'monthlyBudget', // 월간 예산
|
||||
'chartData', // 차트 데이터
|
||||
// 'dontShowWelcome' 키는 삭제 목록에서 제외
|
||||
];
|
||||
|
||||
// 모든 관련 데이터 키 삭제
|
||||
dataKeys.forEach(key => {
|
||||
console.log(`삭제 중: ${key}`);
|
||||
localStorage.removeItem(key);
|
||||
});
|
||||
|
||||
// 기본 데이터로 초기화
|
||||
clearAllTransactions();
|
||||
clearAllCategoryBudgets();
|
||||
clearAllBudgetData();
|
||||
|
||||
// 추가적으로 사용자 기기에 저장된 모든 데이터 검사 (역순으로 루프)
|
||||
for (let i = localStorage.length - 1; i >= 0; i--) {
|
||||
const key = localStorage.key(i);
|
||||
if (key && key !== 'dontShowWelcome' && ( // dontShowWelcome 키는 제외
|
||||
key.includes('expense') ||
|
||||
key.includes('budget') ||
|
||||
key.includes('transaction') ||
|
||||
key.includes('analytics') ||
|
||||
key.includes('spending') ||
|
||||
key.includes('financial') ||
|
||||
key.includes('chart') ||
|
||||
key.includes('month') ||
|
||||
key.includes('sync') ||
|
||||
key.includes('total') ||
|
||||
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));
|
||||
|
||||
// dontShowWelcome 값 복원 (백업한 값이 있는 경우)
|
||||
if (dontShowWelcomeValue) {
|
||||
console.log('resetAllData - dontShowWelcome 값 복원:', dontShowWelcomeValue);
|
||||
localStorage.setItem('dontShowWelcome', dontShowWelcomeValue);
|
||||
|
||||
// 복원 확인
|
||||
const restoredValue = localStorage.getItem('dontShowWelcome');
|
||||
console.log('resetAllData - 복원 후 dontShowWelcome 값:', restoredValue);
|
||||
}
|
||||
|
||||
console.log('모든 데이터가 초기화되었습니다.');
|
||||
};
|
||||
// 데이터 초기화 함수
|
||||
resetAllData
|
||||
} from './storage';
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
|
||||
import { useCallback, useEffect } from 'react';
|
||||
import { BudgetPeriod } from './types';
|
||||
import { toast } from '@/components/ui/use-toast';
|
||||
@@ -10,7 +9,7 @@ import {
|
||||
clearAllTransactions,
|
||||
clearAllCategoryBudgets,
|
||||
clearAllBudgetData
|
||||
} from './storageUtils';
|
||||
} from './storage';
|
||||
|
||||
export const useBudgetState = () => {
|
||||
// 각 상태 관리 훅 사용
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { resetAllData } from '@/contexts/budget/storageUtils';
|
||||
import { resetAllData } from '@/contexts/budget/storage';
|
||||
import { resetAllStorageData } from '@/utils/storageUtils';
|
||||
|
||||
export const useDataInitialization = (resetBudgetData?: () => void) => {
|
||||
|
||||
Reference in New Issue
Block a user