Fix budget data persistence issue

Addresses the problem where budget data was not persisting across page transitions, causing budget and expense information to disappear from the expense page and only expense data to appear on the analytics page.
This commit is contained in:
gpt-engineer-app[bot]
2025-03-16 07:29:25 +00:00
parent 84553d4fee
commit 23ba0f7e90
5 changed files with 158 additions and 113 deletions

View File

@@ -1,72 +1,47 @@
import { useCallback } from 'react';
import { BudgetPeriod, BudgetData } from '../types';
import { toast } from '@/components/ui/use-toast';
import { BudgetData, BudgetPeriod } from '../types';
// 확장된 예산 목표 업데이트 훅
/**
* 확장된 예산 업데이트 기능을 제공하는 훅
*/
export const useExtendedBudgetUpdate = (
budgetData: BudgetData,
categoryBudgets: Record<string, number>,
handleBudgetGoalUpdate: (type: BudgetPeriod, amount: number) => void,
handleBudgetGoalUpdate: (type: BudgetPeriod, amount: number, newCategoryBudgets?: Record<string, number>) => void,
updateCategoryBudgets: (newCategoryBudgets: Record<string, number>) => void
) => {
// 확장된 예산 목표 업데이트 함수
/**
* 확장된 예산 업데이트 함수
* 월간 예산 및 카테고리 예산을 함께 업데이트
*/
const extendedBudgetGoalUpdate = useCallback((
type: BudgetPeriod,
amount: number,
newCategoryBudgets?: Record<string, number>
) => {
try {
console.log(`확장된 예산 목표 업데이트 호출: ${type}, 금액: ${amount}`);
// 카테고리 예산이 직접 업데이트된 경우
if (newCategoryBudgets) {
console.log('카테고리 예산 직접 업데이트:', newCategoryBudgets);
updateCategoryBudgets(newCategoryBudgets);
return;
}
// 월간 예산을 업데이트하고 일일, 주간도 자동 계산
if (type === 'monthly') {
console.log('월간 예산 업데이트:', amount);
if (amount <= 0) return; // 예산이 0 이하면 업데이트하지 않음
const ratio = amount / (budgetData.monthly.targetAmount || 1); // 0으로 나누기 방지
const updatedCategoryBudgets: Record<string, number> = {};
// 비율에 따라 카테고리 예산 업데이트
Object.keys(categoryBudgets).forEach(category => {
updatedCategoryBudgets[category] = Math.round(categoryBudgets[category] * ratio);
});
// 모든 카테고리가 0인 경우 (초기 상태)
const allZero = Object.values(categoryBudgets).every(value => value === 0);
if (allZero) {
// 카테고리 간 균등 분배
const categories = Object.keys(categoryBudgets);
const perCategoryAmount = Math.round(amount / categories.length);
categories.forEach(category => {
updatedCategoryBudgets[category] = perCategoryAmount;
});
}
console.log('업데이트된 카테고리 예산:', updatedCategoryBudgets);
updateCategoryBudgets(updatedCategoryBudgets);
} else {
// 일일이나 주간 예산이 직접 업데이트되는 경우
console.log(`${type} 예산 직접 업데이트:`, amount);
handleBudgetGoalUpdate(type, amount);
}
} catch (error) {
console.error('예산 목표 업데이트 중 오류:', error);
toast({
title: "예산 업데이트 실패",
description: "예산 목표를 업데이트하는 중 오류가 발생했습니다.",
variant: "destructive"
});
console.log(`확장된 예산 업데이트: 타입=${type}, 금액=${amount}, 카테고리 예산 포함=${!!newCategoryBudgets}`);
// 기본 예산 업데이트
handleBudgetGoalUpdate(type, amount);
// 카테고리 예산도 함께 업데이트 (있는 경우)
if (newCategoryBudgets) {
console.log('카테고리 예산 업데이트:', newCategoryBudgets);
updateCategoryBudgets(newCategoryBudgets);
}
}, [budgetData, categoryBudgets, handleBudgetGoalUpdate, updateCategoryBudgets]);
// 데이터 저장 시간 기록 - 동일 세션의 다른 컴포넌트에서 변경 감지 용도
localStorage.setItem('lastBudgetUpdateTime', new Date().toISOString());
// 이벤트 발생
try {
window.dispatchEvent(new Event('budgetDataUpdated'));
window.dispatchEvent(new Event('categoryBudgetsUpdated'));
} catch (error) {
console.error('이벤트 발생 오류:', error);
}
}, [handleBudgetGoalUpdate, updateCategoryBudgets]);
return { extendedBudgetGoalUpdate };
};