Files
zellyy-finance/src/contexts/budget/hooks/useBudgetDataState.ts
2025-03-19 07:27:10 +09:00

164 lines
5.5 KiB
TypeScript

import { useState, useEffect, useCallback } from 'react';
import { BudgetData, BudgetPeriod } from '../types';
import {
loadBudgetDataFromStorage,
saveBudgetDataToStorage,
clearAllBudgetData
} from '../storage';
import { toast } from '@/components/ui/use-toast';
import {
calculateUpdatedBudgetData,
calculateSpentAmounts
} from '../budgetUtils';
import { Transaction } from '../types';
// 예산 데이터 상태 관리 훅
export const useBudgetDataState = (transactions: Transaction[]) => {
const [budgetData, setBudgetData] = useState<BudgetData>(loadBudgetDataFromStorage());
const [selectedTab, setSelectedTab] = useState<BudgetPeriod>("daily");
const [isInitialized, setIsInitialized] = useState(false);
// 초기 로드 및 이벤트 리스너 설정 - 최적화된 버전
useEffect(() => {
// 예산 데이터 로드 함수 - 비동기 처리로 변경
const loadBudget = async () => {
try {
console.log('예산 데이터 로드 시도 중...');
// 비동기 작업을 마이크로태스크로 지연
await new Promise<void>(resolve => queueMicrotask(() => resolve()));
const loadedData = loadBudgetDataFromStorage();
// 새로 로드한 데이터와 현재 데이터가 다를 때만 업데이트
if (JSON.stringify(loadedData) !== JSON.stringify(budgetData)) {
// 상태 업데이트를 마이크로태스크로 지연
queueMicrotask(() => {
setBudgetData(loadedData);
console.log('예산 데이터 업데이트 완료');
});
}
// 초기화 상태 업데이트
if (!isInitialized) {
queueMicrotask(() => {
setIsInitialized(true);
});
}
} catch (error) {
console.error('예산 데이터 로드 중 오류:', error);
}
};
// 초기 로드 - 지연 시간 추가
setTimeout(() => {
loadBudget();
}, 100); // 지연된 초기 로드
// 필수 이벤트만 등록
const handleBudgetUpdate = () => loadBudget();
// 필수 이벤트만 등록
const budgetUpdateHandler = () => handleBudgetUpdate();
window.addEventListener('budgetDataUpdated', budgetUpdateHandler);
return () => {
window.removeEventListener('budgetDataUpdated', budgetUpdateHandler);
};
}, [isInitialized, budgetData]);
// 트랜잭션 변경 시 지출 금액 업데이트
useEffect(() => {
if (transactions.length > 0 && isInitialized) {
console.log('트랜잭션 변경으로 인한 예산 데이터 업데이트. 트랜잭션 수:', transactions.length);
try {
// 지출 금액 업데이트
const updatedBudgetData = calculateSpentAmounts(transactions, budgetData);
// 변경이 있을 때만 저장
if (JSON.stringify(updatedBudgetData) !== JSON.stringify(budgetData)) {
// 상태 및 스토리지 모두 업데이트
setBudgetData(updatedBudgetData);
saveBudgetDataToStorage(updatedBudgetData);
// 저장 시간 업데이트
localStorage.setItem('lastBudgetSaveTime', new Date().toISOString());
}
} catch (error) {
console.error('예산 데이터 업데이트 중 오류:', error);
}
}
}, [transactions, budgetData, isInitialized]);
// 예산 목표 업데이트 함수
const handleBudgetGoalUpdate = useCallback((
type: BudgetPeriod,
amount: number,
newCategoryBudgets?: Record<string, number>
) => {
try {
console.log(`예산 목표 업데이트: ${type}, 금액: ${amount}`);
// 금액이 유효한지 확인
if (isNaN(amount) || amount <= 0) {
console.error('유효하지 않은 예산 금액:', amount);
toast({
title: "예산 설정 오류",
description: "유효한 예산 금액을 입력해주세요.",
variant: "destructive"
});
return;
}
// 예산 업데이트 (카테고리 예산이 있든 없든 무조건 실행)
const updatedBudgetData = calculateUpdatedBudgetData(budgetData, type, amount);
console.log('새 예산 데이터:', updatedBudgetData);
// 상태 및 스토리지 둘 다 업데이트
setBudgetData(updatedBudgetData);
saveBudgetDataToStorage(updatedBudgetData);
// 저장 시간 업데이트
localStorage.setItem('lastBudgetSaveTime', new Date().toISOString());
} catch (error) {
console.error('예산 목표 업데이트 중 오류:', error);
toast({
title: "예산 업데이트 실패",
description: "예산 목표를 업데이트하는데 문제가 발생했습니다.",
variant: "destructive"
});
}
}, [budgetData]);
// 예산 데이터 초기화 함수
const resetBudgetData = useCallback(() => {
try {
console.log('예산 데이터 초기화');
clearAllBudgetData();
setBudgetData(loadBudgetDataFromStorage());
} catch (error) {
console.error('예산 데이터 초기화 중 오류:', error);
toast({
title: "예산 초기화 실패",
description: "예산 데이터를 초기화하는데 문제가 발생했습니다.",
variant: "destructive"
});
}
}, []);
// 예산 데이터 변경 시 로그 기록
useEffect(() => {
console.log('최신 예산 데이터:', budgetData);
}, [budgetData]);
return {
budgetData,
selectedTab,
setSelectedTab,
handleBudgetGoalUpdate,
resetBudgetData
};
};