Fix budget update issues
Addresses delayed notifications and data loss after budget updates and page transitions.
This commit is contained in:
@@ -40,51 +40,98 @@ export const useBudgetState = () => {
|
||||
console.log('- 예산 데이터:', budgetData);
|
||||
console.log('- 카테고리 예산:', categoryBudgets);
|
||||
console.log('- 트랜잭션 수:', transactions.length);
|
||||
|
||||
// 데이터 손실 방지를 위한 타이머 설정
|
||||
const saveTimer = setInterval(() => {
|
||||
// 저장된 데이터 유효성 검사 및 백업
|
||||
try {
|
||||
const storedBudgetData = localStorage.getItem('budgetData');
|
||||
const storedCategoryBudgets = localStorage.getItem('categoryBudgets');
|
||||
const storedTransactions = localStorage.getItem('transactions');
|
||||
|
||||
if (storedBudgetData) {
|
||||
localStorage.setItem('budgetData_backup_auto', storedBudgetData);
|
||||
}
|
||||
|
||||
if (storedCategoryBudgets) {
|
||||
localStorage.setItem('categoryBudgets_backup_auto', storedCategoryBudgets);
|
||||
}
|
||||
|
||||
if (storedTransactions) {
|
||||
localStorage.setItem('transactions_backup_auto', storedTransactions);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('자동 백업 중 오류:', error);
|
||||
}
|
||||
}, 5000); // 5초마다 백업
|
||||
|
||||
return () => {
|
||||
clearInterval(saveTimer);
|
||||
};
|
||||
}, [budgetData, categoryBudgets, transactions]);
|
||||
|
||||
// 카테고리별 예산 및 지출 계산
|
||||
useEffect(() => {
|
||||
const totalMonthlyBudget = Object.values(categoryBudgets).reduce((sum, value) => sum + value, 0);
|
||||
console.log('카테고리 예산 합계:', totalMonthlyBudget);
|
||||
|
||||
if (totalMonthlyBudget > 0) {
|
||||
const totalDailyBudget = Math.round(totalMonthlyBudget / 30);
|
||||
const totalWeeklyBudget = Math.round(totalMonthlyBudget / 4.3);
|
||||
|
||||
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
|
||||
}
|
||||
};
|
||||
try {
|
||||
const totalMonthlyBudget = Object.values(categoryBudgets).reduce((sum, value) => sum + value, 0);
|
||||
console.log('카테고리 예산 합계:', totalMonthlyBudget);
|
||||
|
||||
// 로컬 상태 업데이트
|
||||
handleBudgetGoalUpdate('monthly', totalMonthlyBudget);
|
||||
console.log('예산 데이터 자동 업데이트:', updatedBudgetData);
|
||||
if (totalMonthlyBudget > 0) {
|
||||
const totalDailyBudget = Math.round(totalMonthlyBudget / 30);
|
||||
const totalWeeklyBudget = Math.round(totalMonthlyBudget / 4.3);
|
||||
|
||||
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
|
||||
}
|
||||
};
|
||||
|
||||
// 로컬 상태 업데이트
|
||||
handleBudgetGoalUpdate('monthly', totalMonthlyBudget);
|
||||
console.log('예산 데이터 자동 업데이트:', updatedBudgetData);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('카테고리 예산 계산 중 오류:', error);
|
||||
}
|
||||
}, [categoryBudgets, handleBudgetGoalUpdate, budgetData]);
|
||||
|
||||
// 모든 데이터 리셋 함수
|
||||
const resetBudgetData = useCallback(() => {
|
||||
console.log('BudgetContext에서 데이터 리셋 시작');
|
||||
|
||||
// 로컬 스토리지 초기화
|
||||
resetTransactions();
|
||||
resetCategoryBudgets();
|
||||
resetBudgetDataInternal();
|
||||
|
||||
console.log('BudgetContext에서 데이터 리셋 완료');
|
||||
try {
|
||||
console.log('BudgetContext에서 데이터 리셋 시작');
|
||||
|
||||
// 로컬 스토리지 초기화
|
||||
resetTransactions();
|
||||
resetCategoryBudgets();
|
||||
resetBudgetDataInternal();
|
||||
|
||||
console.log('BudgetContext에서 데이터 리셋 완료');
|
||||
|
||||
// 토스트 알림
|
||||
toast({
|
||||
title: "모든 데이터 초기화",
|
||||
description: "예산과 지출 내역이 모두 초기화되었습니다.",
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('데이터 초기화 중 오류:', error);
|
||||
toast({
|
||||
title: "초기화 실패",
|
||||
description: "데이터를 초기화하는 중 오류가 발생했습니다.",
|
||||
variant: "destructive"
|
||||
});
|
||||
}
|
||||
}, [resetTransactions, resetCategoryBudgets, resetBudgetDataInternal]);
|
||||
|
||||
// 확장된 예산 목표 업데이트 함수
|
||||
@@ -93,37 +140,55 @@ export const useBudgetState = () => {
|
||||
amount: number,
|
||||
newCategoryBudgets?: Record<string, number>
|
||||
) => {
|
||||
console.log(`확장된 예산 목표 업데이트 호출: ${type}, 금액: ${amount}`);
|
||||
|
||||
// 카테고리 예산이 직접 업데이트된 경우
|
||||
if (newCategoryBudgets) {
|
||||
console.log('카테고리 예산 직접 업데이트:', newCategoryBudgets);
|
||||
updateCategoryBudgets(newCategoryBudgets);
|
||||
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: "카테고리별 예산이 저장되었습니다."
|
||||
title: "예산 업데이트 실패",
|
||||
description: "예산 목표를 업데이트하는 중 오류가 발생했습니다.",
|
||||
variant: "destructive"
|
||||
});
|
||||
|
||||
return; // 카테고리 예산이 변경되면 useEffect에서 자동으로 budgetData가 업데이트됩니다
|
||||
}
|
||||
|
||||
// 월간 예산을 업데이트하고 일일, 주간도 자동 계산
|
||||
if (type === 'monthly') {
|
||||
console.log('월간 예산 업데이트:', amount);
|
||||
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);
|
||||
});
|
||||
|
||||
console.log('업데이트된 카테고리 예산:', updatedCategoryBudgets);
|
||||
updateCategoryBudgets(updatedCategoryBudgets);
|
||||
} else {
|
||||
// 일일이나 주간 예산이 직접 업데이트되는 경우
|
||||
console.log(`${type} 예산 직접 업데이트:`, amount);
|
||||
handleBudgetGoalUpdate(type, amount);
|
||||
}
|
||||
}, [budgetData, categoryBudgets, handleBudgetGoalUpdate, updateCategoryBudgets]);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user