Refactor useBudgetState into smaller files
Refactors the `useBudgetState.ts` file into smaller, more manageable files to improve code organization and maintainability. No functionality is changed.
This commit is contained in:
@@ -1,82 +1,43 @@
|
||||
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { BudgetData, BudgetPeriod, Transaction } from './types';
|
||||
import { useCallback, useEffect } from 'react';
|
||||
import { BudgetPeriod } from './types';
|
||||
import { toast } from '@/components/ui/use-toast';
|
||||
import {
|
||||
loadTransactionsFromStorage,
|
||||
saveTransactionsToStorage,
|
||||
loadCategoryBudgetsFromStorage,
|
||||
saveCategoryBudgetsToStorage,
|
||||
loadBudgetDataFromStorage,
|
||||
saveBudgetDataToStorage,
|
||||
import { useTransactionState } from './hooks/useTransactionState';
|
||||
import { useCategoryBudgetState } from './hooks/useCategoryBudgetState';
|
||||
import { useBudgetDataState } from './hooks/useBudgetDataState';
|
||||
import { useCategorySpending } from './hooks/useCategorySpending';
|
||||
import {
|
||||
clearAllTransactions,
|
||||
clearAllCategoryBudgets,
|
||||
clearAllBudgetData
|
||||
} from './storageUtils';
|
||||
import {
|
||||
calculateCategorySpending,
|
||||
calculateSpentAmounts,
|
||||
calculateUpdatedBudgetData
|
||||
} from './budgetUtils';
|
||||
|
||||
export const useBudgetState = () => {
|
||||
// 상태 초기화
|
||||
const [selectedTab, setSelectedTab] = useState<BudgetPeriod>("daily");
|
||||
const [transactions, setTransactions] = useState<Transaction[]>([]);
|
||||
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 = () => {
|
||||
const storedTransactions = loadTransactionsFromStorage();
|
||||
setTransactions(storedTransactions);
|
||||
};
|
||||
|
||||
loadTransactions();
|
||||
|
||||
// 지출 내역이 변경될 때마다 업데이트되도록 이벤트 리스너를 추가합니다
|
||||
window.addEventListener('storage', loadTransactions);
|
||||
return () => {
|
||||
window.removeEventListener('storage', loadTransactions);
|
||||
};
|
||||
}, []);
|
||||
|
||||
// 지출 계산 및 업데이트
|
||||
useEffect(() => {
|
||||
// 스토리지에서 데이터 로드
|
||||
const loadedBudgetData = loadBudgetDataFromStorage();
|
||||
|
||||
// 지출 금액 업데이트
|
||||
const updatedBudgetData = calculateSpentAmounts(transactions, loadedBudgetData);
|
||||
|
||||
// 상태 및 스토리지 모두 업데이트
|
||||
setBudgetData(updatedBudgetData);
|
||||
saveBudgetDataToStorage(updatedBudgetData);
|
||||
|
||||
// 트랜잭션 변경 내용도 저장
|
||||
saveTransactionsToStorage(transactions);
|
||||
|
||||
// 로컬 이벤트 발생 (다른 컴포넌트에서 변경 감지하도록)
|
||||
window.dispatchEvent(new Event('budgetDataUpdated'));
|
||||
}, [transactions]);
|
||||
// 각 상태 관리 훅 사용
|
||||
const {
|
||||
transactions,
|
||||
addTransaction,
|
||||
updateTransaction,
|
||||
deleteTransaction,
|
||||
resetTransactions
|
||||
} = useTransactionState();
|
||||
|
||||
const {
|
||||
categoryBudgets,
|
||||
setCategoryBudgets,
|
||||
updateCategoryBudgets,
|
||||
resetCategoryBudgets
|
||||
} = useCategoryBudgetState();
|
||||
|
||||
const {
|
||||
budgetData,
|
||||
selectedTab,
|
||||
setSelectedTab,
|
||||
handleBudgetGoalUpdate,
|
||||
resetBudgetData: resetBudgetDataInternal
|
||||
} = useBudgetDataState(transactions);
|
||||
|
||||
const { getCategorySpending } = useCategorySpending(transactions, categoryBudgets);
|
||||
|
||||
// 카테고리별 예산 및 지출 계산
|
||||
useEffect(() => {
|
||||
@@ -84,61 +45,49 @@ export const useBudgetState = () => {
|
||||
const totalDailyBudget = Math.round(totalMonthlyBudget / 30);
|
||||
const totalWeeklyBudget = Math.round(totalMonthlyBudget / 4.3);
|
||||
|
||||
setBudgetData(prev => {
|
||||
const updatedBudgetData = {
|
||||
daily: {
|
||||
targetAmount: totalDailyBudget,
|
||||
spentAmount: prev.daily.spentAmount,
|
||||
remainingAmount: totalDailyBudget - prev.daily.spentAmount
|
||||
},
|
||||
weekly: {
|
||||
targetAmount: totalWeeklyBudget,
|
||||
spentAmount: prev.weekly.spentAmount,
|
||||
remainingAmount: totalWeeklyBudget - prev.weekly.spentAmount
|
||||
},
|
||||
monthly: {
|
||||
targetAmount: totalMonthlyBudget,
|
||||
spentAmount: prev.monthly.spentAmount,
|
||||
remainingAmount: totalMonthlyBudget - prev.monthly.spentAmount
|
||||
}
|
||||
};
|
||||
|
||||
// 저장 과정 강화 - 예산 데이터 저장
|
||||
try {
|
||||
saveBudgetDataToStorage(updatedBudgetData);
|
||||
console.log('예산 데이터가 저장되었습니다:', updatedBudgetData);
|
||||
} catch (error) {
|
||||
console.error('예산 데이터 저장 중 오류:', error);
|
||||
const updatedBudgetData = {
|
||||
daily: {
|
||||
targetAmount: totalDailyBudget,
|
||||
spentAmount: budgetData.daily.spentAmount,
|
||||
remainingAmount: totalDailyBudget - budgetData.daily.spentAmount
|
||||
},
|
||||
weekly: {
|
||||
targetAmount: totalWeeklyBudget,
|
||||
spentAmount: budgetData.weekly.spentAmount,
|
||||
remainingAmount: totalWeeklyBudget - budgetData.weekly.spentAmount
|
||||
},
|
||||
monthly: {
|
||||
targetAmount: totalMonthlyBudget,
|
||||
spentAmount: budgetData.monthly.spentAmount,
|
||||
remainingAmount: totalMonthlyBudget - budgetData.monthly.spentAmount
|
||||
}
|
||||
|
||||
return updatedBudgetData;
|
||||
});
|
||||
|
||||
// 저장 과정 강화 - 카테고리 예산 저장
|
||||
try {
|
||||
saveCategoryBudgetsToStorage(categoryBudgets);
|
||||
console.log('카테고리 예산이 저장되었습니다:', categoryBudgets);
|
||||
} catch (error) {
|
||||
console.error('카테고리 예산 저장 중 오류:', error);
|
||||
}
|
||||
};
|
||||
|
||||
// 로컬 이벤트 발생 (다른 컴포넌트에서 변경 감지하도록)
|
||||
window.dispatchEvent(new Event('categoryBudgetsUpdated'));
|
||||
}, [categoryBudgets]);
|
||||
}, [categoryBudgets, budgetData]);
|
||||
|
||||
// 카테고리별 지출 계산
|
||||
const getCategorySpending = () => {
|
||||
return calculateCategorySpending(transactions, categoryBudgets);
|
||||
};
|
||||
// 모든 데이터 리셋 함수
|
||||
const resetBudgetData = useCallback(() => {
|
||||
console.log('BudgetContext에서 데이터 리셋 시작');
|
||||
|
||||
// 로컬 스토리지 초기화
|
||||
resetTransactions();
|
||||
resetCategoryBudgets();
|
||||
resetBudgetDataInternal();
|
||||
|
||||
console.log('BudgetContext에서 데이터 리셋 완료');
|
||||
}, [resetTransactions, resetCategoryBudgets, resetBudgetDataInternal]);
|
||||
|
||||
// 예산 목표 업데이트 함수
|
||||
const handleBudgetGoalUpdate = (type: BudgetPeriod, amount: number, newCategoryBudgets?: Record<string, number>) => {
|
||||
// 확장된 예산 목표 업데이트 함수
|
||||
const extendedBudgetGoalUpdate = (
|
||||
type: BudgetPeriod,
|
||||
amount: number,
|
||||
newCategoryBudgets?: Record<string, number>
|
||||
) => {
|
||||
// 카테고리 예산이 직접 업데이트된 경우
|
||||
if (newCategoryBudgets) {
|
||||
setCategoryBudgets(newCategoryBudgets);
|
||||
|
||||
// 저장 과정 추가
|
||||
saveCategoryBudgetsToStorage(newCategoryBudgets);
|
||||
updateCategoryBudgets(newCategoryBudgets);
|
||||
|
||||
toast({
|
||||
title: "카테고리 예산 업데이트 완료",
|
||||
@@ -157,48 +106,11 @@ export const useBudgetState = () => {
|
||||
updatedCategoryBudgets[category] = Math.round(categoryBudgets[category] * ratio);
|
||||
});
|
||||
|
||||
setCategoryBudgets(updatedCategoryBudgets);
|
||||
saveCategoryBudgetsToStorage(updatedCategoryBudgets);
|
||||
updateCategoryBudgets(updatedCategoryBudgets);
|
||||
} else {
|
||||
// 일일이나 주간 예산이 직접 업데이트되는 경우
|
||||
const updatedBudgetData = calculateUpdatedBudgetData(budgetData, type, amount);
|
||||
setBudgetData(updatedBudgetData);
|
||||
saveBudgetDataToStorage(updatedBudgetData);
|
||||
handleBudgetGoalUpdate(type, amount);
|
||||
}
|
||||
|
||||
toast({
|
||||
title: "목표 업데이트 완료",
|
||||
description: `${type === 'daily' ? '일일' : type === 'weekly' ? '주간' : '월간'} 목표가 ${amount.toLocaleString()}원으로 설정되었습니다.`
|
||||
});
|
||||
};
|
||||
|
||||
// 트랜잭션 추가 함수 추가
|
||||
const addTransaction = (newTransaction: Transaction) => {
|
||||
setTransactions(prev => {
|
||||
const updated = [newTransaction, ...prev];
|
||||
saveTransactionsToStorage(updated);
|
||||
return updated;
|
||||
});
|
||||
};
|
||||
|
||||
// 트랜잭션 업데이트 처리
|
||||
const updateTransaction = (updatedTransaction: Transaction) => {
|
||||
setTransactions(prev => {
|
||||
const updated = prev.map(transaction =>
|
||||
transaction.id === updatedTransaction.id ? updatedTransaction : transaction
|
||||
);
|
||||
saveTransactionsToStorage(updated);
|
||||
return updated;
|
||||
});
|
||||
};
|
||||
|
||||
// 트랜잭션 삭제 함수 추가
|
||||
const deleteTransaction = (transactionId: string) => {
|
||||
setTransactions(prev => {
|
||||
const updated = prev.filter(transaction => transaction.id !== transactionId);
|
||||
saveTransactionsToStorage(updated);
|
||||
return updated;
|
||||
});
|
||||
};
|
||||
|
||||
return {
|
||||
@@ -210,7 +122,7 @@ export const useBudgetState = () => {
|
||||
addTransaction,
|
||||
updateTransaction,
|
||||
deleteTransaction,
|
||||
handleBudgetGoalUpdate,
|
||||
handleBudgetGoalUpdate: extendedBudgetGoalUpdate,
|
||||
getCategorySpending,
|
||||
resetBudgetData
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user